ASP.NET data annotations: how to share with a JSON client?

We have two data models: read-only Models that go to the client, and Management models that send modified data back. In fact, they are the same, and everyone has data annotations such as this on them:

// Require nothing but one or more digits
[RegularExpression(@"^\d+$", ErrorMessage = "*")]
public string productid {get;set;}

All of our messages go through controller methods using JsonResultand Json().

How can a client honor these data annotations? In particular, how can a jQuery plugin use it, such as validate, these regular expressions, required ranges, etc. for use?

We have an answer that includes a header object with nested collections (e.g. a list of product lists). We thought that Regex could exist in the header and then apply to all fields of the form. But how could we translate annotations into a serialized JSON object?

+3
source share
1 answer

See this blog post.

Essentially, you call the MVC Html Helper method <% Html.EnableClientValidation();%>, which displays some JSON on the page. Then there is a translation method in MicrosoftMvcJQueryValidation.js, which sends jquery confirmation with data annotations for each field.


Update for comments

HTMLFormElements mvc, . , ViewData.ModelMetadata, . , MetaDataProvider, , MVC3 RC, ( )

:

+2

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


All Articles