In previous article, I have provided sample article for Bootstrap Modal Validation in ASP.NET MVC, but in this article we will be validating form inside Bootstrap Modal Pop in ASP.NET Core MVC using Data annotation in ASP.NET Core

Step 1: Create a new ASP.NET Core MVC project in your Visual Studio, so Navigate to File-> New -> Project and then select "Web" From left-pane, select "ASP.NET Core Web-Application" from right-pane, give a name to your project (ModalValidationInNETCoreMVC) and then click "OK", as shown in the below image

Modal Validation in ASP NET Core MVC

On the Next-screen, choose "Web-application (Model-View-Controller)" as template and click "OK"

modal-validation-asp-net-core

So Visual Studio can auto-generate basic files for .NET Core MVC web-application.

Note: If you are using Visual Studio 2019/2022, you can open VS -> Click on "Create new Project" -> Select ASP.NET Core (Model- View-Controller) project template and then select .NET Core version, then create project.

Step 2: Create a new class by right-clicking on "Models" folder, then select "Add" -> "New Item" -> Select "Code", name your new class as "Student.cs" and use the below code

using System.ComponentModel.DataAnnotations;

namespace ModalValidationInASPNETCoreMVC.Models
{
    public class Student
    {
        [Required] //make this field required
        [StringLength(50)] // adds character limit = 50
        public string Name { get; set; }

        [Required] // make this field required
        [EmailAddress] // Validates that the property has an email format.
        public string Email { get; set; }
    }
}

In the above code, we have created Student Class, which is using Data Annotation attributes like StringLength, Required and EmailAddress to validate fields of Razor form.

Step 3: Navigate to "Views"-> "Home" -> "Index.cshtml" and use the below code, to create bootstrap Pop-up Modal and load Partial view in it.

@model ModalValidationInASPNETCoreMVC.Models.Student

@{
    ViewData["Title"] = "Main Page";
}
<br/>
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">Open Modal</button>


<form asp-action="Index" asp-controller="Home" data-ajax-method="POST" data-ajax="true" data-ajax-update="studentFormDetails" data-ajax-complete="OnComplete">
    <div id="exampleModal" class="modal fade" tabindex="-1" role="dialog" data-backdrop="static">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">Student Details Form</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body" id="studentFormDetails">
                    <partial name="~/Views/Home/_StudentDetailsView.cshtml" model="@Model" />
                </div>
                <div class="modal-footer">
                    <input id="btnSubmit" type="submit" value="Submit" class="btn btn-primary" />
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
                </div>
            </div>
        </div>
    </div>
</form>

@section Scripts{
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>
    <script type="text/javascript">
        function OnComplete() {
            $("#exampleModal").modal("hide");
        }
    </script>
}

You can also note, in the above code we are using jQuery-unobtrusive validation

<script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
<script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.js"></script>

Do not forget to add these libraries, otherwise validation won't work.

Step 4: Navigate to HomeController.cs and use the below code

using Microsoft.AspNetCore.Mvc;
using ModalValidationInASPNETCoreMVC.Models;

namespace ModalValidationInASPNETCoreMVC.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Index()
        {
            return View();
        }

        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Index(Student student)
        {
            if (ModelState.IsValid)
            {
                ModelState.Clear();
                //yes Model is valid
                //save student details in database
                return View();
            }
            //return Model with error
            return View();
        }
    }
}

Step 5: Now, we need to add partial view _StudentDetailsView.cshtml, so right-click on "Views" folder, select "Add" and then select "View", check it as partial view, and name it "_StudentDetailsView", use the below code in it.

@model ModalValidationInASPNETCoreMVC.Models.Student

@Html.AntiForgeryToken()
<div class="form-group">
    <label asp-for="Name" class="control-label"></label>
    <input asp-for="Name" class="form-control" autocomplete="off"  />
    <span asp-validation-for="Name" class="text-danger"></span>
</div>
<div class="form-group">
    <label asp-for="Email" class="control-label"></label>
    <input asp-for="Email" placeholder="Enter your Email Address" autocomplete="off" class="form-control" />
    <span asp-validation-for="Email"></span>
</div>

In the above code, we are using ASP.NET Core Tag helpers to show validation error and to bind form with Model.

Step 6: We are done, just build your project and run it in your browser, you will see output like below

modal-validation-asp-net-core-mvc-min.gif

As you can see above output, when we are trying to submit empty form, we are getting error validation messages, which is because of Data annotations used in Student.cs

You may also like to read:

Creating GridView in ASP.NET Core MVC with Paging

Model Validation in ASP.NET Core MVC (With Custom validation example)

File upload in ASP.NET Core MVC (Single or Multiple files)

Form Submit in ASP.NET Core MVC using Tag Helpers

Read OR Generate QR Code in ASP.NET Core

Creating Google charts in ASP.NET Core MVC

Convert PDF to Image in C# (Console Application Example)

AWS vs DigitalOcean (Which is better? with Price Comparison)

Understanding Unit testing in C# With Example