Question

In some ASP.NET MVC code examples, I see references to ModelState.IsValid, and in other examples I see references to ViewData.ModelState.IsValid.

In my initial research, I see:

  • ModelState is a public property in Controller class.
  • ViewData is a public property in ControllerBase class.

Is there a difference between the two? Why have both?

Was it helpful?

Solution

They reference the exact same thing, if you look at the code for System.Web.Mvc.Controller class you will see the implementation for ModelState is:

   public ModelStateDictionary ModelState
    {
      get
      {
        return this.ViewData.ModelState;
      }
    }

I would say it is simply there for easy of use in your own Controller implementations.

OTHER TIPS

They're one and the same, and you could use ViewData.ModelState.Errors in your controller - having it as a property on ControllerBase is really just a convenience, allowing you to shorten it to ModelState.Errors (and the even more often used ModelState.IsValid).

Although the main use of ModelState from an "end developer"'s perspective is in the controller, ViewData is used as a container for all data that's communicated between the controller and the view. Which is why it also needs to include ModelState - because, although you'd rarely use it directly in the view, ModelState is where e.g. many of the HtmlHelper methods actually get the values from by default when rendering the view from a POST action - rather than Model.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top