开发者

ASP.NET Data Annotations: How to share with a JSON client?

We have two data models: read only View Models going to the client and "Control" Models sending modified data back. Essentially, they are the same, and all have Data Annotations like this on them:

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

All of our communication goes through Controller Methods using JsonResult and Json().

How could the client honor these data annotations? Specifically, how could a JQuery plugin like validate receive these regular expressions, required, ranges, etc. to use for itself?

We have a response that includes a header object with nested collections (like a product list List). We were thinking the Regex could exist in the header, then applied to all the form fields. But how could we translate the annotations to a JSON serialized obje开发者_Go百科ct?


See this blog post.

Essentially you call an MVC Html Helper method <% Html.EnableClientValidation();%> that outputs some JSON onto the page. Then there is a translation method in the MicrosoftMvcJQueryValidation.js that feeds jquery validate with the data annotations for each field.


Update for comments

If you are rendering the HTMLFormElements without using mvc controls it will be much more difficult. You will probably need to look at the ViewData.ModelMetadata to access the data annotations. Possibly need to use a custom MetaDataProvider I would consider going to MVC3 RC so I could use th unobtrusive validation (data attribute)

Here are some links:

  • Brad Wilson: Unobtrusive Client Validation
  • Brad Wilson: Model Metadata
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜