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

Razor Pages ajax modals with validation in ASP.NET Core

x Razor Pages ajax modals with validation in ASP.NET Core

In the source code,  Shows how to create ajax powered Bootstrap modals in Razor Pages and learn how to dynamically load partial view page content  (_Create.chstml) in the main view page using asp.net core. how to send/save your partial view page data in your controller via ajax, and how to validate it using Razor Pages as a backend technology.


Create project

Create a new project in visual studio 2019 or greater than 2019. I’m using Visual Studio Community 2019. Pick the “Create a new project” menu option, then select “ASP.NET Core Web Application”.

Add EmployeeInfoViewodel.cs class under Models folder

Our modal will contain a simple contact form with only three fields: First Name, Last Name, and Address.

The first thing you need to do is to create a model/class with these fields. Create Models directory and then create a EmployeeInfoViewModel.cs file:

public class EmployeeInfoViewModel
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Address{ get; set; }
}

A few keypoints I want you to notice here are:

  • @model directive which points to our model/EmployeeInfoViewodel class
  • Full modal markup (powered by Bootstrap)
  • asp-page-handler form attribute, which points to Razor Pages handler (needed later to save modal contents)


Create a new view page Create.cshtml and call _Create.cshtml view page in Create.cshtml like as given below

 In .NET CORE

<partial name="_Create" />

In ASP.NET MVC

  @Html.Partial("_Create")


Validation from ViewModel like as given below

 Using this namespace

using System.ComponentModel.DataAnnotations;

Throw Validation message in the view page

[Required(ErrorMessage = "Name Required!")]

Display Label in view page from Viewmodel

 [Display(Name ="First Name")]

Bootstrap modal HTML popup 

<div class="container">

  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>
  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>
  </div>
</div>
Mahira  khanna

Mahira khanna

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

0 Comments



Report Response