Context: creating a jsonP service with mvc controller methods which provides a definition of formfields including all validation rules.
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.
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;}
}
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." }]}
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));
}
}
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.