ModelState (System.Web.Mvc) with example

ModelState refers to a set of name and value pairs submitted to the server during a post. This allows you to save the value submitted to the server and check for errors associated with each value. Let's see how this works with an example.

The following is a sample model code. It has three properties: MovieID, Movie and Release Year.

SampleViewModel.cs

public class SampleViewModel
{
    public int MovieID { get; set; }
    public string Movie { get; set; }
    public int ReleaseYear { get; set; }
}

Below is an index view code. Here you can see how the model properties are bonded to the TagHelpers.

Index.cshtml

@{
    ViewData["Title"] = "ModelState Example";
    Layout = null;
}

@model SampleViewModel

<form action="/Home/index"  method="post">
    <div>
        <div>
            <label for="MovieID">Movie ID:</label>
            <input id="MovieID" name="MovieID" type="text">
        </div>
        <div>
            <label for="Movie">Movie:</label>
            <input id="Movie" name="Movie" type="text">
        </div>
        <div>
            <label for="ReleaseYear">Release Year:</label>
            <input id="ReleaseYear" name="ReleaseYear" type="text">
        </div>
        <div>
            <input type="submit" value="Save">
        </div>
    </div>
</form>

The following is a controller code. There are two actions involved. The first action passes the SampleViewModel to view, the second obtain a ViewModel with values.

HomeController.cs

public IActionResult Index()
{
    SampleViewModel model = new SampleViewModel();
    return View(model);
}

[HttpPost]
public IActionResult Index(SampleViewModel model)
{
    if (!ModelState.IsValid)
    {
        return View(model);
    }
    return RedirectToAction("Sample");
}

The following screenshot is taken while running the app through the breakpoint in ModelState. In the picture, you can see the properties of the ModelState.

Count: It shows the number of properties in the ModelState. In the screenshot, it has three (MovieIT, Movie and Release Year).

ErrorCount: The number of error added to the ModelState

HasReachedMaxErrors: This is a Boolean value. If ModelState reaches the maximum error it will return to true. That would be true when Microsoft.AspNetCore.Mvc.ModelBinding.TooManyModelErrorsException throws.

IsValid: This is a Boolean. This indicates whether the ModelState values are valid or not.

Keys: It contains the key sequence.


MaxAllowedError: This allows ModelStateDictionary to obtain or set the maximum allowable ModelState errors in this instance. The default value is 200.

Root: It is a root entry for ModelStateDictionary.

Values: It helps to set the value sequence.


I hope this article is helpful to you. Keep coding.

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

SignalR with JavaScript in ASP.NET Core MVC

Localization in ASP.NET Core MVC with Example