开发者

Validating only selected fields using ASP.NET MVC 2 and Data Annotations

开发者 https://www.devze.com 2022-12-24 12:22 出处:网络
I\'m using Data Annotations with ASP.NET MVC 2 as demonstrated in this post: http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

I'm using Data Annotations with ASP.NET MVC 2 as demonstrated in this post:

http://weblogs.asp.net/scottgu/archive/2010/01/15/asp-net-mvc-2-model-validation.aspx

Everythi开发者_StackOverflowng works fine when creating / updating an entity where all required property values are specified in the form and valid.

However, what if I only want to update some of the fields? For example, let's say I have an Account entity with 20 fields, but I only want to update Username and Password?

ModelState.IsValid validates against all the properties, regardless of whether they are referenced in the submitted form.

How can I get it to validate only the fields that are referenced in the form?


The recommended practice is to use a model specific to each view. In your case this this would be a model with only username and password properties. When the user submits the form, you would map the properties to your actual domain object in the controller. For this I use Automapper to simplify the mapping. This does mean you'd need to set your validation rules in each view model though.


One possible solution:

http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/

0

精彩评论

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

关注公众号