how does aspnet mvc modelState know how to check validity of properties?
I have class Employee
public class Employee { public string LastName { get; set; } public decimal Salary { get; set; } }
In EmployeesController, method
[HttpPostAttribute] public ActionResult Create(Employee employee) { }
If a user enters “1,2,3” in the Salary field of the Employee form, the ModelState becomes invalid.
- “1,2,3” is a valid C# decimal number, but more important
- why/how/on what basis does Asp.Net MVC check the validity of the input string?
I found n开发者_C百科o official documentation on this. Can anybody shed light on this?
enter link description hereIt's how the DecimalModelBinder works (see second response, basically the Decimal Model Binder is returning false for 1, 2 and/or 3...). It's see's 1, 2 and 3 as integers only.
Try passing in 1.00 and it'll take it.
It's all about the magic this is the ModelBinders and here. Here's a nice overview.
Here's a sample of how to extend it.
Another overview with some tips for taking advantage of the model binding.
You can also download the source as a way to get to know what it's doing. The codeplex site has some nice information that might help you as well.
EDIT - To answer your questions in your comments...
You can change the error message by using Data Annotations. Check out this also. You can create your own Data Annotations as well if you don't like how the default / built-in work. You can also localize your validation messages.
Here's another nice overview that goes through some of the techniques you can employ for validation. You can add validation directly to the model as well as using Annotations. Of particular interest for you may be validating using the IDataErrorInfo Interface, the IValidatableObject Interface and/or Remote Validation.
精彩评论