Model Binding and Validation Errors

I am using asp.net MVC3 and I am very new to this technology.

My models are designed in such a way that the properties will throw validation errors if the data is invalid. In this case, the properties are not set with invalid data.

When I redisplay my editing-view, validation error messages are shown; however the values that the user previously entered are gone because the model that it is bound to only contains the old-valid data.

For example, say I had a Person class and the Name property cannot be a null or empty string otherwise it throws a validation exception and prevents the property from being set. Now say the user removes the value from the Name property and tries to save the Person from the web. A validation exception will be thrown and handled properly to add the error to the ModelState so that it is displayed on the screen; however the old value for the Name is redisplayed since the invalid, empty string never made it into the property.

I do not know how to solve this problem and any advice on the issue would be greatly appreciated.


My advise is allow invalid data but use validation attributes. You wont save invalid entities so there is no problem and this is the standard approach these days. If you don't want do that, there is no easy solution. Most simple solution would be using the info from Request.Form


You should implement IValidatableObject to performe this kind of validation at server side.

From MSDN IValidatableObject Interface:

Provides a way for an object to be invalidated.

Theres an exemple here Using IValidatableObject Custom Validation, also from MSDN.


The solution to this problem was to create a ViewModel that allowed invalid data to be entered into this. This solution also simplified my ModelBinder classes because it took on most of the work.

链接地址: http://www.djcxy.com/p/58302.html

上一篇: 什么是ASP.NET MVC中的WebApi [FromUri]等价物?

下一篇: 模型绑定和验证错误