ASP.NET MVC Controller post method unit test: ModelState.IsValid always true

You’re trying to test two different things at the same time. The controller is not reponsible for validating the model state, only for behaving differently based on the result of that validation. So your unit tests for the controller shouldn’t try to test the validation, that should be done in a different test. In my … Read more

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

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

ASP.NET MVC How to convert ModelState errors to json

You can put anything you want to inside the select clause: var errorList = (from item in ModelState where item.Value.Errors.Any() select item.Value.Errors[0].ErrorMessage).ToList(); EDIT: You can extract multiple errors into separate list items by adding a from clause, like this: var errorList = (from item in ModelState.Values from error in item.Errors select error.ErrorMessage).ToList(); Or: var errorList … 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

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