【问题标题】:How to serialize a model with all validation attributes from the individual properties?如何序列化具有来自各个属性的所有验证属性的模型?
【发布时间】:2011-09-18 17:40:33
【问题描述】:

上下文:使用 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." }]}

非常感谢任何帮助或指点。

【问题讨论】:

    标签: json asp.net-mvc-3 serialization json.net validationattribute


    【解决方案1】:

    这将构造一个字典,其中包含基于数据注释属性的给定属性的验证属性:

    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));
        }
    }
    

    然后,您应该在自定义 JSON 序列化代码中使用您的属性序列化 validationAttributes 字典。

    【讨论】:

    • 谢谢,这正是我想要的。
    • 对 Web Api 2 有什么建议吗?
    【解决方案2】:

    在提出这个问题时这可能不存在,但现在有一种更新的方法可以将验证作为字典进行:

    @Html.GetUnobtrusiveValidationAttributes("FieldName")
    

    https://msdn.microsoft.com/en-us/library/system.web.mvc.htmlhelper.getunobtrusivevalidationattributes(v=vs.108).aspx


    更新:当应该验证时,我无法为某些字段返回一个空集,所以我实际上已经接受了接受的解决方案。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多