上下文:使用mvc控制器方法创建jsonP服务,该方法提供包含所有验证规则的表单字段的定义.
我的问题是我不知道如何序列化验证属性.在常规Mvc视图中使用不显眼的验证时,我更喜欢与Razor序列化的格式相同的验证属性.
为了序列化为json,我使用NewtonSoft.Json(4.0.2).
型号示例:
公共课简介{
[required(ErrorMessage="This field is required.")] [StringLength(25,ErrorMessage="Max 25 chars.")] public string Firstname{get;set;} }
首选序列化javascript的示例:
{"Firstname": "John","ValidationRules":[{"data-val-required":"This field is required.","data-val-length-max":25,"data-val-length":"Max 25 chars." }]}
非常感谢任何帮助或指示.
解决方法
这将基于数据注释属性构造具有给定属性的验证属性的字典:
var Metadata = ModelMetadataProviders.Current.GetMetadataForProperty(null,typeof(MyModel),"MyProperty"); var validationRules = Metadata.GetValidators(ControllerContext).SelectMany(v => v.GetClientValidationRules()); var validationAttributes = new Dictionary<string,string>(); foreach (ModelClientValidationRule rule in validationRules) { string key = "data-val-" + rule.ValidationType; validationAttributes.Add(key,HttpUtility.HtmlEncode(rule.ErrorMessage ?? string.Empty)); key = key + "-"; foreach (KeyValuePair<string,object> pair in rule.ValidationParameters) { validationAttributes.Add(key + pair.Key,HttpUtility.HtmlAttributeEncode( pair.Value != null ? Convert.ToString(pair.Value,CultureInfo.InvariantCulture) : string.Empty)); } }