How to serialize a model with all validation attributes from the individual properties?

不问归期 提交于 2019-12-04 05:42:31

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

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

This probably didn't exist at the time of this question, but there's now an updated way of doing getting the validation as a dictionary:

@Html.GetUnobtrusiveValidationAttributes("FieldName")

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


UPDATE: I am having trouble with it returning an empty set for some fields when there should be validation, so I've actually gone with the accepted solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!