How to Validate a Model in a jQuery Postback

2019-09-09 12:43发布

问题:

If I have a model;

Name
  [Required]
  FirstName
  [Required]
  LastName

If I create the model in my jQuery postback thus;

Name name = new Name{ FirstName = param1, LastName = param2 };

Is there a way I can validate it using the data annotations that decorate the fields?

This is not happening in a postback event on the view, it's happening within a jQuery postback

thanks

回答1:

I am assuming that you are sending the data to the Controller in Json format. If you are, you need to use a custom JsonValueProvider that does not intrude with Model Validation. One is provided for you in the ASP.NET MVC Futures assembly and Phil Haack wrote a blog post with instructions on how to register it in your application startup.

http://haacked.com/archive/2010/04/15/sending-json-to-an-asp-net-mvc-action-method-argument.aspx