How to check if model is valid inside the razor view in Asp.Net MVC

To check if your model is valid from inside a Razor view in ASP.NET MVC, you can utilize the ModelState.IsValid property. This property indicates whether there are any model validation errors.

Here are multiple code examples showing how to check if the model is valid from inside a Razor view:

  1. Basic Check:
@if (ModelState.IsValid)
{
    <p>Model is valid</p>
}
else
{
    <p>Model is not valid</p>
}
  1. Conditional Rendering:
@if (ModelState.IsValid)
{
    <div class="alert alert-success">
        Model is valid
    </div>
}
else
{
    <div class="alert alert-danger">
        Model is not valid
    </div>
}
  1. Using Validation Summary:
@if (!ModelState.IsValid)
{
    <div class="alert alert-danger">
        <h4>Validation Errors</h4>
        @Html.ValidationSummary(true)
    </div>
}
  1. Displaying Validation Errors for Specific Fields:
@if (!ModelState.IsValid)
{
    <div class="alert alert-danger">
        <h4>Validation Errors</h4>
        <ul>
            @foreach (var key in ModelState.Keys)
            {
                foreach (var error in ModelState[key].Errors)
                {
                    <li>@error.ErrorMessage</li>
                }
            }
        </ul>
    </div>
}
  1. Using Razor syntax with HTML attributes:
    <div class="form-group @(ModelState.IsValid ? "" : "has-error")">
    @Html.LabelFor(m => m.PropertyName)
    @Html.TextBoxFor(m => m.PropertyName, new { @class = "form-control" })
    @Html.ValidationMessageFor(m => m.PropertyName, "", new { @class = "text-danger" })
</div>

In all these examples, ModelState.IsValid is used to determine if the model is valid. Depending on whether the model is valid or not, different content or styling is rendered in the view. You can choose the approach that best fits your scenario and design requirements.

 
About Us | Terms of Use | Privacy Policy | Disclaimer | Contact Us Copyright © 2012-2024 CodingFusion
50+ C# Programs for beginners to practice