如何序列化与来自各个属性的所有验证属性的模式? [英] How to serialize a model with all validation attributes from the individual properties?

查看:145
本文介绍了如何序列化与来自各个属性的所有验证属性的模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

上下文:创建具有MVC控制器方法JSONP服务提供formfields在内的所有验证规则的定义

Context: creating a jsonP service with mvc controller methods which provides a definition of formfields including all validation rules.

我的问题是,我不知道如何序列验证属性。我preFER验证​​的,因为它们是由剃刀定期的mvc视图中使用不引人注目的验证序列化时相同的格式属性。

My problem is that I do not know how to serialize the validation attributes. I prefer the validation attributes in the same format as they are serialized by Razor when using unobtrusive validation in regular Mvc views.

有关序列化到JSON我使用NewtonSoft.Json(4.0.2)。

For serializing to json I use NewtonSoft.Json (4.0.2).

模型的例子:
        公共类档案{

Example of model: public class Profile{

    [Required(ErrorMessage="This field is required.")]
    [StringLength(25, ErrorMessage="Max 25 chars.")]
    public string Firstname{get;set;}
    }

$ P $的例子pferred序列化的JavaScript:

Example of preferred serialized javascript:

     {"Firstname": "John", 
      "ValidationRules":[{"data-val-required":"This field is required.", "data-val-length-max":25, "data-val-length":"Max 25 chars." }]}

任何帮助或指针是非常AP preciated。

Any help or pointers are very much appreciated.

推荐答案

这将构造一个字典,根据数据注解给定属性的属性验证属性:

This will construct a dictionary with the validation attributes for a given property based on the data annotation attributes:

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

您应该然后序列化validationAttributes字典,在您的自定义JSON序列化code你的财产。

You should then serialize the validationAttributes dictionary with your property in your custom JSON serialization code.

这篇关于如何序列化与来自各个属性的所有验证属性的模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆