<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>asp net 5 modelstate &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/asp-net-5-modelstate/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Wed, 28 Apr 2021 05:35:42 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>asp net 5 modelstate &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>Know Further About ModelState in ASP.NET 5.0</title>
		<link>https://topreviewhostingasp.net/know-further-about-modelstate-in-asp-net-5-0/</link>
					<comments>https://topreviewhostingasp.net/know-further-about-modelstate-in-asp-net-5-0/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Wed, 28 Apr 2021 05:21:39 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[asp net 5]]></category>
		<category><![CDATA[asp net 5 modelstate]]></category>
		<category><![CDATA[asp net 5 tips]]></category>
		<category><![CDATA[asp net 5 tutorial]]></category>
		<category><![CDATA[asp.net tips]]></category>
		<category><![CDATA[asp.net tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=2956</guid>

					<description><![CDATA[In this post, we&#8217;re going to explain what the ModelState is, and what it is used for. We&#8217;ll also show how to use it to validate our POSTed inputs, and do simple custom validation. Here we go! What is the ModelState? In short, the ModelState is a collection of name and value pairs that are submitted to the server [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In this post, we&#8217;re going to explain what the <code>ModelState</code> is, and what it is used for. We&#8217;ll also show how to use it to validate our POSTed inputs, and do simple custom validation. Here we go!</p>



<h2 class="wp-block-heading" id="what-is-the-modelstate">What is the ModelState?</h2>



<p>In short, the <code>ModelState</code> 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.</p>



<p><code>ModelState</code> is a property of a <code>Controller</code> instance, and can be accessed from any class that inherits from <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.controller?view=aspnetcore-5.0">Microsoft.AspNetCore.Mvc.Controller</a>.</p>



<p>The <code>ModelState</code> has two purposes: to store and submit POSTed name-value pairs, and to store the validation errors associated with each value.</p>



<p>All right, enough of the boring explanation. It&#8217;s code time!</p>



<h2 class="wp-block-heading" id="the-sample-project">The Sample Project</h2>



<p>You can use <a href="https://github.com/exceptionnotfound/ModelStateAspNet5Demo">sample project on Github</a>.</p>



<h2 class="wp-block-heading" id="setup">Setup</h2>



<p>Let&#8217;s start writing the code we need to demonstrate how the <code>ModelState</code> works in ASP.NET 5 MVC. We will begin by creating a straightforward view model, <code>AddMovieVM</code>:</p>



<pre class="wp-block-code"><code>namespace ModelStateCoreDemo.ViewModels
{
    public class AddMovieVM
    {
        public string Title { get; set; }
        public DateTime ReleaseDate { get; set; }
        public int RuntimeMinutes { get; set; }
    }
}</code></pre>



<p>We will also create a corresponding <code>Add.cshtml</code> view in the folder Views/Movie:</p>



<pre class="wp-block-code"><code>@model ModelStateCoreDemo.ViewModels.AddMovieVM

&lt;h2&gt;Add Movie&lt;/h2&gt;

&lt;form asp-action="AddPost" asp-controller="Movie" method="post"&gt;
    &lt;div&gt;
        &lt;div&gt;
            &lt;label asp-for="Title"&gt;&lt;/label&gt;
            &lt;input type="text" asp-for="Title" /&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;label asp-for="Description"&gt;&lt;/label&gt;
            &lt;input type="text" asp-for="Description" /&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;label asp-for="ReleaseDate"&gt;&lt;/label&gt;
            &lt;input type="date" asp-for="ReleaseDate" /&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;label asp-for="RuntimeMinutes"&gt;&lt;/label&gt;
            &lt;input type="number" asp-for="RuntimeMinutes" /&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;input type="submit" value="Save" /&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/form&gt; </code></pre>



<p>Lastly, we create a <code>MovieController</code> class with two actions:</p>



<pre class="wp-block-code"><code>using Microsoft.AspNetCore.Mvc;
using ModelStateCoreDemo.ViewModels;

public class MovieController : Controller
{
    [HttpGet("movies/add")]
    public IActionResult Add()
    {
        AddMovieVM model = new AddMovieVM();
        return View(model);
    }

    [HttpPost("movies/add/post")]
    public IActionResult AddPost(AddMovieVM model)
    {
        if(!ModelState.IsValid)
        {
            return View("Add", model);
        }

        return RedirectToAction("Index");
    }
}</code></pre>



<p>When we submit our Add form to the POST action, all of the values we entered on the view will show up in the correct properties in the <code>AddMovieVM</code> instance. But how did they get there?</p>



<h2 class="wp-block-heading" id="peeking-into-the-modelstate">Peeking Into the ModelState</h2>



<p>Let&#8217;s take a peek at the rendered HTML for the Add page:</p>



<pre class="wp-block-code"><code>&lt;h2&gt;Add Movie&lt;/h2&gt;

&lt;form method="post" action="/movies/add"&gt;
    &lt;div&gt;
        &lt;div&gt;
            &lt;label for="Title"&gt;Title&lt;/label&gt;
            &lt;input type="text" 
                   id="Title" 
                   name="Title" 
                   value=""&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;label for="ReleaseDate"&gt;ReleaseDate&lt;/label&gt;
            &lt;input type="date" 
                   id="ReleaseDate" 
                   name="ReleaseDate" 
                   value="0001-01-01"&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;label for="RuntimeMinutes"&gt;RuntimeMinutes&lt;/label&gt;
            &lt;input type="number" 
                   id="RuntimeMinutes" 
                   name="RuntimeMinutes" 
                   value="0"&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;input type="submit" value="Save"&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/form&gt; </code></pre>



<p>When this page is POSTed to the server, all values in <code>&lt;input&gt;</code> tags will be submitted as name-value pairs.</p>



<p>At the point when ASP.NET 5 MVC receives a POST action, it takes all of the name-value pairs and adds them as individual instances of <code>ModelStateEntry</code> to an instance of <code>ModelStateDictionary</code>. Both <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.modelbinding.modelstateentry?view=aspnetcore-5.0">ModelStateEntry</a> and <a href="https://docs.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.mvc.modelbinding.modelstatedictionary?view=aspnetcore-5.0">ModelStateDictionary</a> have pages in Microsoft&#8217;s documentation.</p>



<p>In Visual Studio, we can use the Locals window to show what exactly this looks like:</p>



<figure class="wp-block-image size-large"><img fetchpriority="high" decoding="async" width="907" height="486" class="wp-image-2957" src="https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_1.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_1.png 907w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_1-300x161.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_1-768x412.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_1-50x27.png 50w" sizes="(max-width: 907px) 100vw, 907px" /></figure>



<p>We can see from the <code>Values</code> property of the <code>ModelState</code> that there are three name-value pairs: one each for <code>Title</code>, <code>ReleaseDate</code>, and <code>RuntimeMinutes</code>.</p>



<p>Each of the items in the results for the <code>Values</code> is of type <code>ModelStateEntry</code>. But what exactly is this?</p>



<h2 class="wp-block-heading" id="what-s-in-the-modelstateentry">What&#8217;s In the ModelStateEntry?</h2>



<p>Here&#8217;s what those same input values look like, taken from the same debugger session.</p>



<figure class="wp-block-image size-large"><img decoding="async" width="907" height="483" class="wp-image-2958" src="https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_2.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_2.png 907w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_2-300x160.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_2-768x409.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_2-50x27.png 50w" sizes="(max-width: 907px) 100vw, 907px" /></figure>



<p>You can see that each <code>ModelStateEntry</code> contains properties like <code>RawValue</code>, which holds the raw value that was submitted, and <code>Key</code>, which holds the name of said value. ASP.NET 5 MVC creates all of these instances for us automatically when we submit a POST action that has associated data. ASP.NET 5 MVC is therefore making what was a complicated set of data into easier-to-use instances.</p>



<p>There are two important functions of the <code>ModelState</code> that we still need to discuss: errors and validation.</p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://www.asphostportal.com"><img decoding="async" width="300" height="271" class="wp-image-2953 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/04/ahp-banner-aspnet-mvc-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/04/ahp-banner-aspnet-mvc-01.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/ahp-banner-aspnet-mvc-01-50x45.png 50w" sizes="(max-width: 300px) 100vw, 300px" /></a></figure>
</div>



<h2 class="wp-block-heading" id="validation-errors-in-the-modelstate">Validation Errors in the ModelState</h2>



<p>Let&#8217;s make a quick modification to our <code>AddMovieVM</code> class so that we are now implementing validation on its fields.</p>



<pre class="wp-block-code"><code>public class AddMovieVM
{
    [Required(ErrorMessage = "The Title cannot be blank.")]
    [DisplayName("Title: ")]
    public string Title { get; set; }

    [DisplayName("Release Date: ")]
    public DateTime ReleaseDate { get; set; }

    [Required(ErrorMessage = "The Runtime Minutes cannot be blank.")]
    [Range(1, int.MaxValue, 
           ErrorMessage = "The Runtime Minutes must be greater than 0.")]
    [DisplayName("Runtime Minutes: ")]
    public int RuntimeMinutes { get; set; }
}
</code></pre>



<p>We have added validation to these fields using the <code>[Required]</code> and <code>[Range]</code> validation attributes, as well as specifying the name to use in <code>&lt;label&gt;</code> tags with the <code>[DisplayName]</code> attribute. If the <code>Title</code>, the <code>Description</code>, or the <code>RuntimeMinutes</code> field fails validation, we need to show an error message.</p>



<p>To do that, we must make some changes to our view; we will need to add a <code>&lt;span&gt;</code> tag with the property <code>asp-validation-for</code> set for each input:</p>



<pre class="wp-block-code"><code>@model ModelStateCoreDemo.ViewModels.AddMovieVM

&lt;h2&gt;Add Movie&lt;/h2&gt;

&lt;form asp-action="AddPost" asp-controller="Movie" method="post"&gt;
    &lt;div&gt;
        &lt;div&gt;
            &lt;label asp-for="Title"&gt;&lt;/label&gt;
            &lt;input type="text" asp-for="Title"/&gt;
            &lt;span asp-validation-for="Title"&gt;&lt;/span&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;label asp-for="ReleaseDate"&gt;&lt;/label&gt;
            &lt;input type="date" asp-for="ReleaseDate" /&gt;
            &lt;span asp-validation-for="ReleaseDate"&gt;&lt;/span&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;label asp-for="RuntimeMinutes"&gt;&lt;/label&gt;
            &lt;input type="number" asp-for="RuntimeMinutes" /&gt;
            &lt;span asp-validation-for="RuntimeMinutes"&gt;&lt;/span&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;input type="submit" value="Save"/&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/form&gt; </code></pre>



<p>The <code>asp-validation-for</code> property will render the validation errors message in the specified <code>&lt;span&gt;</code> element, with some default CSS already applied.</p>



<p>Let&#8217;s take a look at what happens to our collection of <code>ModelStateEntry</code> instances when an invalid object is submitted to the server:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="906" height="484" class="wp-image-2959" src="https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_3.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_3.png 906w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_3-300x160.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_3-768x410.png 768w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_3-50x27.png 50w" sizes="(max-width: 906px) 100vw, 906px" /></figure>



<p>Note that the <code>IsValid</code> property of the <code>ModelState</code> is now <code>false</code>, and the <code>ValidationState</code> property of the invalid <code>ModelStateEntry</code> instances is now <code>Invalid</code>.</p>



<p>When ASP.NET 5 MVC creates the model state for the submitted values, it also iterates through each property in the view model and validates said property using the attributes associated to that property. In certain cases, attributes are implicitly evaluated (in our particular case, <code>ReleaseDate</code> has an implicit <code>[Required]</code> attribute because its type is <code>DateTime</code> and therefore cannot be blank).</p>



<p>If any errors are found, they are added to the <code>Errors</code> property of each <code>ModelStateEntry</code>. There is also a property <code>ErrorCount</code> on the <code>ModelState</code> that shows all errors found during the validation. If errors exist for a given POSTed value, the <code>ValidationState</code> of that property becomes <code>Invalid</code>.</p>



<p>In this case, because at least one of the <code>ModelStateEntry</code> instances has an error, the <code>IsValid</code> property of <code>ModelState</code> is now <code>false</code>.</p>



<p>What all of this means is merely this: we are using ASP.NET 5 MVC the way it was intended to be used. The <code>ModelState</code> stores submitted values, calculates the errors associated with each, and allows our controllers to check for said errors as well as the <code>IsValid</code> flag. In many scenarios, this is all we need, and all of it happens behind the scenes!</p>



<h2 class="wp-block-heading" id="custom-validation">Custom Validation</h2>



<p>There are times when we need more complex validation than ASP.NET 5 provides natively.</p>



<p>Let&#8217;s pretend that we now need a new field, <code>Description</code>, for each movie. Let&#8217;s also pretend that in addition to not allowing <code>Description</code> to be blank, it also cannot be exactly the same as the <code>Title</code>.</p>



<p>First, we can add the <code>Description</code> field to the view model:</p>



<pre class="wp-block-code"><code>public class AddMovieVM
{
    [Required(ErrorMessage = "The Title cannot be blank.")]
    [DisplayName("Title: ")]
    public string Title { get; set; }

    [Required(ErrorMessage = "The Description cannot be blank.")]
    [DisplayName("Description: ")]
    public string Description { get; set; }

    [DisplayName("Release Date: ")]
    public DateTime ReleaseDate { get; set; }

    [Required(ErrorMessage = "The Runtime Minutes cannot be blank.")]
    [Range(1, int.MaxValue, 
           ErrorMessage = "The Runtime Minutes must be greater than 0.")]
    [DisplayName("Runtime Minutes: ")]
    public int RuntimeMinutes { get; set; }
}</code></pre>



<p>We can also add it to the view:</p>



<pre class="wp-block-code"><code>@model ModelStateCoreDemo.ViewModels.AddMovieVM

&lt;h2&gt;Add Movie&lt;/h2&gt;

&lt;form asp-action="AddPost" asp-controller="Movie" method="post"&gt;
    &lt;div&gt;
        &lt;div&gt;
            &lt;label asp-for="Title"&gt;&lt;/label&gt;
            &lt;input type="text" asp-for="Title" /&gt;
            &lt;span asp-validation-for="Title"&gt;&lt;/span&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;label asp-for="Description"&gt;&lt;/label&gt;
            &lt;input type="text" asp-for="Description" /&gt;
            &lt;span asp-validation-for="Description"&gt;&lt;/span&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;label asp-for="ReleaseDate"&gt;&lt;/label&gt;
            &lt;input type="date" asp-for="ReleaseDate" /&gt;
            &lt;span asp-validation-for="ReleaseDate"&gt;&lt;/span&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;label asp-for="RuntimeMinutes"&gt;&lt;/label&gt;
            &lt;input type="number" asp-for="RuntimeMinutes" /&gt;
            &lt;span asp-validation-for="RuntimeMinutes"&gt;&lt;/span&gt;
        &lt;/div&gt;
        &lt;div&gt;
            &lt;input type="submit" value="Save" /&gt;
        &lt;/div&gt;
    &lt;/div&gt;
&lt;/form&gt; </code></pre>



<p>When the form is POSTed, we can do custom validation in our controllers. To check that the <code>Description</code> does not exactly match the <code>Title</code>, we can modify the POST action on our <code>MovieController</code> class like so:</p>



<pre class="wp-block-code"><code>public class MovieController : Controller
{
    //... Other methods

    [HttpPost("movies/add/post")]
    public IActionResult AddPost(AddMovieVM model)
    {
        if(model.Title == model.Description)
        {
            ModelState.AddModelError("description", 
                "The Description cannot exactly match the Title.");
        }

        if(!ModelState.IsValid)
        {
            return View("Add", model);
        }

        return RedirectToAction("Index");
    }
}</code></pre>



<p>Which will show the error next to the input for <code>Description</code>:</p>



<figure class="wp-block-image size-large"><img loading="lazy" decoding="async" width="626" height="240" class="wp-image-2960 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_4.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_4.png 626w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_4-300x115.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/image_4-50x19.png 50w" sizes="(max-width: 626px) 100vw, 626px" /></figure>



<h2 class="wp-block-heading" id="summary">Summary</h2>



<p>In ASP.NET 5 MVC, the <code>ModelState</code> property of a controller represents the submitted values, and validation errors in those values if such errors exist, during a POST action.</p>



<p>During the POST, the values submitted can be validated, and the validation process uses attributes defined by .NET like <code>[Required]</code> and <code>[Range]</code>. We can do simple custom validation server-side by modifying our controllers.</p>



<p>On views, the <code>asp-validation-for</code> property on a <code>&lt;span&gt;</code> element will show an error message for a specific property of the view model.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/know-further-about-modelstate-in-asp-net-5-0/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
