Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC: ModelState vs. ModelStateDictionary

I have a service which has a method that's called when a certain controller method is triggered.

My service returns a custom result object PlacementResult in which I want to communicate errors that may have happened (validation) back to the controller method.

Should PlacementResult have a ModelState or a ModelStateDictionary to communicate errors back to the controller (and finally view)? How would I string this together?

Finally, how do I get the ModelState/ModelStateDictionary (whichever you tell me I should choose) back into the view (highlighting the appropriate text box, show the error message etc.)?

Thank you !

like image 312
Alex Avatar asked Aug 18 '09 05:08

Alex


People also ask

What is ModelState in ASP NET MVC?

In short, the ModelState is a collection of name and value pairs that are submitted to the server during a POST. It also contains error messages about each name-value pair, if any are found. ModelState is a property of a Controller instance, and can be accessed from any class that inherits from Microsoft.

Why ModelState IsValid is false in MVC?

That's because an error exists; ModelState. IsValid is false if any of the properties submitted have any error messages attached to them. What all of this means is that by setting up the validation in this manner, we allow MVC to just work the way it was designed.

What is the use of ModelState IsValid in MVC?

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.

Why we use ModelState clear ()?

Clear() is required to display back your model object. If you are getting your Model from a form and you want to manipulate the data that came from the client form and write it back to a view, you need to call ModelState. Clear() to clean the ModelState values.


2 Answers

This is a good link that shows how a service can perform validation and communicate the result back to the controller:

http://www.asp.net/mvc/tutorials/validating-with-a-service-layer-cs (fixed link)

like image 145
SO User Avatar answered Sep 19 '22 04:09

SO User


No, you do not want to add a ModelStateDictionary to your result type. There is already a ModelStateDictionary on the Controller (in the ModelState property). It is not appropriate for results to set the controller's model state. That should be done during binding or within the controller action itself. Use a custom model binder if you need to.

Your choose one can see the model state errors by examining the controller's ViewData.ModelState property.

like image 38
Craig Stuntz Avatar answered Sep 21 '22 04:09

Craig Stuntz