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

Context: creating a jsonP service using the mvc controller methods, which provides the definition of form fields, including all validation rules.

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

For serialization in json, I use NewtonSoft.Json (4.0.2).

Model Example: Public Class Profile {

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

Preferred serialized javascript example:

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

Any help or pointers are greatly appreciated.

+6
source share
1 answer

This will build a dictionary with validation attributes for this property based on 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)); } } 

Then you must serialize the validationAttributes dictionary with your property in your custom JSON serialization code.

+7
source

Source: https://habr.com/ru/post/890930/


All Articles