Model validation: Rerun validation (TryValidateModel) in ASP.NET Core MVC

This article is going to explain how to validate the model manually. If you want to calculate the value of a model and assign it to the model, you can use TryValidateModel to validate if the model is valid or not. Let us see with an example of how TryValidateModel works.

The following is SampleViewModel. The [Required] attribute is included for all properties. That is, all properties are mandatory, so it is a must to assign value to them.

public class SampleViewModel
{
    [Required]
    public int MovieID { get; set; }
    [Required]
    public string Movie { get; set; }
    [Required]
    public string DirectedBy { get; set; }
    [Required]
    public int ReleaseYear { get; set; }
}

Next is a controller Index() action method. Here the value is assigned to MovieID and ReleaseYear, but not to DirectedBy and ReleaseYear.

public IActionResult Index()
{
    SampleViewModel model = new SampleViewModel() { 
        MovieID =1,
        ReleaseYear = 2019
    };

    return View(model);
}

The following is the view code. I have added a Validation Summary Tag Helper to list error messages.

@{
    ViewData["Title"] = "TryValidateModel validation";
    Layout = null;
}

@model SampleViewModel

<h4>Validation Summary</h4>

<div asp-validation-summary="All" class="text-danger"></div>

The following image is the output of the code above, you can see that the page here does not list any error message. But in the SampleViewModel model, the [Required] attribute is assigned to all properties. So the page should show the message that Movie and DirectedBy are needed. But it did not show. Let's see how to list the error message.


Below is the modified Index() action method. Here I have added TryValidateModel(model). This will trigger a list of error messages. Let's see the output of this code.

public IActionResult Index()
{
    SampleViewModel model = new SampleViewModel() { 
        MovieID =1,
        ReleaseYear = 2019
    };
    
   TryValidateModel(model);
return View(model); }

The following screenshot shows the result. Here it shows a list of error messages.

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

Comments

Popular posts from this blog

Entity Framework Core (EF) with SQL Server LocalDB

Exploring EventCallback in Blazor: Building Interactive Components

A Step-by-Step Guide to Implementing Identity in ASP.NET Core MVC