find and solve || findandsolve.com
Please wait.....

Validate Pop Up Modal using Ajax in .ASP.NET Core MVC

Download source code from here
Validate Pop Up Modal using Ajax in .ASP.NET Core MVC

In this blog, we are going to explain, how to show validation messages in the bootstrap pop-up modal using ajax with PartilView, without closing the Bootstrap Pop-up modal.


This tutorial focuses on given below

  • Ajax.Beginform
  • Bootstrap Pop-up Modal
  • PartilView
  • ViewModel class
  • Validation from ViewModel Class
  • Create a new view page


Create New Application in visual studio 2019

  • Open your visual studio 2019 or greater than 2019
  • Click on Create a New Project
  • Select ASP.NET Core Web Application and then Next
  • Provide a Project name and confirm or change the Location. Select Create
  • Select the latest version of ASP.NET Core in the drop-down (.NET Core 5.0)and then select Web Application
  • Under Authentication, select Change and set the authentication to Individual User Accounts and then click on Create button


Step 1.

Go to your HomeController(as we have been using a basic template, not an empty MVC project), and create a new action method

public IActionResult Create()
{
    return View();
}

Step 2.

Right-Click inside above created ActionMethod and Click on "Add View" 


When you click on Razor View-Empty you will see like as given below


Step 3.

Place this code in your created view page (Create.cshtml) like as given below.

@{
    ViewBag.Title = "Create";
}
<button type="button" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
    Add New Employee
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-label="Close">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body" id="formStudentId">
              <partial name="_Create" />
            </div>
        </div>
    </div>
</div>
@section scripts{
    <script src="~/lib/jquery-validation/dist/jquery.validate.min.js"></script>
    <script src="~/lib/jquery-validation-unobtrusive/jquery.validate.unobtrusive.min.js"></script>
    <script type="text/javascript">
        $("#employeeInfoId").on("submit", function (event) {
            event.preventDefault();
            $.ajax({
                type: "POST",
                url: "/Home/Create",
                data: $('#employeeInfoId').serialize(),
                contentType: "application/json",
                dataType: "json",
                success: function (response) {
                    alert("Hello")
                }
            });
        });
    </script>
}

 Refer the required js files in your Create.html view, you will need following files

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

Step 4.

Let's create the class EmployeeInfoViewModel.css under the Models folder for validation purposes like as given below.

using System.ComponentModel.DataAnnotations;
namespace ValidationPopu.Models
{
    public class EmployeeInfoViewModel
    {
        [Required]
        [Display(Name ="First Name")]
        public string FirstName { get; set;}
        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }
        [Required]
        public string Address { get; set;}
    }
}

Step 5.

 Create _Create.cshtml partial view, with the below code, to refer EmployeeInfoViewModel.cs Model in it, so that you can validate it before submitting it to the controller.Flow by Step 2

    <form id="employeeInfoId">
        @Html.AntiForgeryToken()
        <span class="alert-danger">
            @Html.ValidationSummary(true)         </span>
        <div class="form-group">
            <label asp-for="FirstName"></label>
            <input asp-for="FirstName" class="form-control" />
            <span asp-validation-for="FirstName" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="LastName"></label>
            <input asp-for="LastName" class="form-control" />
            <span asp-validation-for="LastName" class="text-danger"></span>
        </div>
        <div class="form-group">
            <label asp-for="Address"></label>
            <input asp-for="Address" class="form-control" />
            <span asp-validation-for="Address" class="text-danger"></span>
        </div>
        <div class="modal-footer">
            <input type="submit" class="btn btn-primary" value="Summit" />
        </div>
    </form>

Step 6.

Create Action name in your HomeController.cs like as given below.

Full code in your HomeController.cs

using Microsoft.AspNetCore.Mvc;
using ValidationPopu.Models;
namespace ValidationPopu.Controllers
{
    public class HomeController : Controller
    {
        public IActionResult Create()
        {
            return View();
        }         public PartialViewResult _Create()
        {
            return PartialView();
        } //post method
        [HttpPost]
        [ValidateAntiForgeryToken]
        public IActionResult Create(EmployeeInfoViewModel model)
        {
            return Json(model);
        }
    }
}

Step 7.

Run your application, Got to URL "/Home/Create", and click on "Add New Employee", and try to submit the form without entering details, you will see errors, without page-refresh(reload), these error messages are generated with the help of Data annotation in MVC, you can change these error messages from EmployeeInfoViewModel.cs


Mahira  khanna

Mahira khanna

I have the skills you need for you company blog, website, or other content materials

If findandsolve.com felt valuable to you, feel free to share it.

Comments



Report Response