ASP.NET MVC 3 validation: Are the DataAnnotation a

2019-07-16 02:10发布

问题:

Scott Guthrie blogged about ASP.NET MVC 2: Model Validation little over a year ago and in his post, the controllers were decorated with calls to ModelState.IsValid-method. Since then we've had the ASP.NET MVC 3 which included quite big changes to the validation.

But has the requirement to call the ModelState.IsValid still stayed the same? Are all the DataAnnotation attributes useless if the site visitor has disabled the JavaScript and the site developer has forget to check the value of ModelState.IsValid?

If yes, is there a way around this? Is it for example possible to register a global filter which always remembers to check for the model's validity event if the coder doesn't?

回答1:

The client side validation features would be turned off. This is why you must never rely only on client side validation. It would not affect the model binder which uses the annotations on the server. Here is the relevant text from that blog post...

Because the action method accepts a “Person” object as a parameter, ASP.NET MVC will create a Person object and automatically map the incoming form input values to it. As part of this process, it will also check to see whether the DataAnnotation validation attributes for the Person object are valid. If everything is valid, then the ModelState.IsValid check within our code will return true – in which case we will (eventually) save the Person to a database and then redirect back to the home-page.