What does ModelState.IsValid do?

ModelState.IsValid indicates if it was possible to bind the incoming values from the request to the model correctly and whether any explicitly specified validation rules were broken during the model binding process. In your example, the model that is being bound is of class type Encaissement. Validation rules are those specified on the model by … Read more

ModelState.AddModelError – How can I add an error that isn’t for a property?

I eventually stumbled upon an example of the usage I was looking for – to assign an error to the Model in general, rather than one of it’s properties, as usual you call: ModelState.AddModelError(string key, string errorMessage); but use an empty string for the key: ModelState.AddModelError(string.Empty, “There is something wrong with Foo.”); The error message … Read more

How to figure out which key of ModelState has error

You can check the ViewData.ModelState.Values collection and see what are the Errors. [Httpost] public ActionResult Create(User model) { if(ModelState.IsValid) { //Save and redirect } else { foreach (var modelStateVal in ViewData.ModelState.Values) { foreach (var error in modelStateVal.Errors) { var errorMessage = error.ErrorMessage; var exception = error.Exception; // You may log the errors if you want … Read more

ModelState.IsValid == false, why?

As you are probably programming in Visual studio you’d better take advantage of the possibility of using breakpoints for such easy debugging steps (getting an idea what the problem is as in your case). Just place them just in front / at the place where you check ModelState.isValid and hover over the ModelState. Now you … Read more

Validation: How to inject A Model State wrapper with Ninject?

The solution given by that article mixes validation logic with the service logic. These are two concerns and they should be separated. When your application grows you will quickly find out that validation logic gets complicated and gets duplicated throughout the service layer. I, therefore, like to suggest a different approach. First of all, it … Read more

ASP.NET MVC – How to Preserve ModelState Errors Across RedirectToAction?

I had to solve this problem today myself, and came across this question. Some of the answers are useful (using TempData), but don’t really answer the question at hand. The best advice I found was on this blog post: http://www.jefclaes.be/2012/06/persisting-model-state-when-using-prg.html Basically, use TempData to save and restore the ModelState object. However, it’s a lot cleaner … Read more