CRUD Operation on a Single Page in ASP.NET Core MVC

SPONSOR AD

CRUD Operation on a Single Page in ASP.NET Core MVC using jQuery Ajax

In this article, I will explain How to Perform CRUD Operation on a Single Page in ASP.NET Core MVC using jQuery Ajax with an Example. Please read our previous article discussing How to Host ASP.NET Core Application into the IIS Server.

When do we need to Perform the CRUD Operations on a Single Page?

Performing CRUD (Create, Read, Update, Delete) operations on a single page is commonly associated with the Single Page Application (SPA) model in web development. This approach can be beneficial in several scenarios:

  • Enhanced User Experience: SPAs can provide a more responsive user experience. Since the page does not reload entirely for each operation, interactions feel smoother and faster, similar to a desktop application.
  • Real-time Applications: For applications that require real-time data updates, like chat apps or live dashboards, SPAs can update the relevant parts of the page instantly without needing to reload.
  • Reduced Server Load: SPAs can reduce the load on the server. Since most of the content is loaded once at the beginning, subsequent data exchanges between the client and server typically involve JSON, which is lighter than full-page HTML content.
  • Mobile App Feel: Performing CRUD operations on a single page can provide a similar experience to native mobile applications.
  • Streamlined Development: SPAs can simplify the development process, especially when using modern JavaScript frameworks like React, Angular, or Vue.js, which are designed to handle SPA functionality efficiently.
What is jQuery AJAX?

jQuery AJAX refers to the methods provided by the jQuery library for performing asynchronous HTTP requests. AJAX stands for Asynchronous JavaScript and XML. AJAX allows web pages to be updated asynchronously by exchanging data with a web server in the background. This means updating parts of a web page without reloading the whole page is possible.

When do we need to use jQuery AJAX?

jQuery AJAX is used to make asynchronous HTTP requests to a server from a web page. This is useful in several scenarios:

SPONSOR AD
  • Dynamic Content Loading: If you want to update a part of your web page with data from the server without reloading the entire page. For example, loading more items onto an infinite scroll page or refreshing a section of a page with updated information.
  • Form Submission: AJAX can be used to submit form data to the server and process the response without requiring a page reload. This improves user experience by providing immediate feedback and a smoother interaction.
  • Data Retrieval: You can retrieve data from a server in the background. This is useful for features like auto-complete in search bars, where you need to fetch data based on user input without interrupting their experience.
  • Interacting with APIs: When you need to interact with third-party APIs on the client side, AJAX is a common method for making those HTTP requests and handling the responses.
  • Partial Page Updates: In single-page applications (SPAs) or in situations where only a part of the page needs to be updated based on user actions or other events.
How do you Perform CRUD Operations on a Single Page in ASP.NET Core MVC using jQuery Ajax?

Performing CRUD (Create, Read, Update, Delete) operations on a single page in ASP.NET Core MVC using jQuery Ajax involves several steps. This approach enhances user experience by enabling server interactions without requiring page reloads. Here is the pictorial representation of the Single Page Application that we will develop using jQuery AJAX in ASP.NET Core MVC.

When the user visits the web page, it will display the following. All employee details will be displayed with the option to Edit and Delete an existing employee. Also, we have one option to add a new employee.

How do you Perform CRUD Operations on a Single Page in ASP.NET Core MVC using jQuery Ajax?

When we click on the Add New Employee button, it will open the following Modal Popup and allow us to enter the new Employee Name, Salary, and Department. Here, we also have two options: Add Employee and Close. If we click on the Close button, it will simply Close the modal popup. The Add Employee button is used to add the Employee to the database.

Perform CRUD Operations on a Single Page in ASP.NET Core MVC using jQuery Ajax

Once you enter the Employee details and click on the Add Employee button, it will make an asynchronous call to the server using jQuery AJAX. The server will then insert the new employee into the database and return to the client application from where the Ajax call has been made. Then, immediately, we make another asynchronous call to the server to get the updated employees and update the UI. So, once the Employee is added to the database, immediately, it will reflect in the UI as shown in the below image:

CRUD Operations on a Single Page in ASP.NET Core MVC using jQuery Ajax

SPONSOR AD

Now, if you click the Edit button, another modal popup will open with the prepopulated data. You can update whatever information you want, as shown in the image below. We also have two options here: Update and Close. If you don’t want to update data, then simply click on the Close button, which will close the Modal popup. If you want to update the data, then you need to click on the Update button.

CRUD Operations on a Single Page in ASP.NET Core MVC

Once you update the Employee details and click on the Update button, it will make an asynchronous call to the server using jQuery AJAX. The server will then update the employee information in the database and return to the client application from where we have made the Ajax call. Then, immediately, it will make another asynchronous call to the server to get the updated employees and update the UI. So, once the Employee is updated in the database, it will reflect in the UI as shown in the below image:

CRUD Operations in ASP.NET Core MVC using jQuery AJAX

Now, click on the Delete button. Another modal popup will open and ask you for the delete confirmation before actually deleting the data, as shown in the image below. Here, we also have two options: Delete and Cancel. If you don’t want to delete the employee, click on the Cancel button to close the Modal popup. If you want to delete the employee, you need to click the Delete button.

How to Perform CRUD Operations in ASP.NET Core MVC using jQuery AJAX

Once you click on the Delete button, it will make an asynchronous call to the server using jQuery AJAX. The server will then delete the employee from the database and return to the client application from where we have made the Ajax call. Then, immediately, it will make another asynchronous call to the server to get the updated employees and update the UI. So, once the Employee is deleted from the database, immediately, it will reflect in the UI as shown in the below image:

How to Perform CRUD Operations in ASP.NET Core MVC using jQuery AJAX with Example

SPONSOR AD

Let us proceed and see how we can implement the above application in ASP.NET Core MVC using jQuery AJAX.

Set Up Your ASP.NET Core MVC Project

Create a new ASP.NET Core MVC project. Ensure you have the necessary NuGet packages for MVC. Also, as we are going to interact with the database, so please install the following two packages from the NuGet Package Manager:

  • EF Core DB Provider: Microsoft.EntityFrameworkCore.SqlServer
  • EF Core Tools: Microsoft.EntityFrameworkCore.Tools
Create Model

Define a model class representing the data on which you want to perform CRUD operations. For example, let us add the following Emplpyee model within the Models folder. We are going to perform CRUD operations using the following employee model.

namespace CRUDUsingQueryAJAX.Models
{
    public class Employee
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public long Salary { get; set; }
        public string Department { get; set; }
    }
}
Creating DbContext Class:

We will perform the database CRUD operation using the Entity Framework Core Code First Approach. So, create the following EmployeeDBContext class within the Models folder, and please change the database connection string details.

using Microsoft.EntityFrameworkCore;
namespace CRUDUsingQueryAJAX.Models
{
    public class EmployeeDBContext : DbContext
    {

        //Constructor calling the Base DbContext Class Constructor
        public EmployeeDBContext() : base()
        {
        }

        //OnConfiguring() method is used to select and configure the data source
        protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
        {
            //Configuring the Connection String
            optionsBuilder.UseSqlServer(@"Server=LAPTOP-6P5NK25R\SQLSERVER2022DEV;Database=EmployeeDB;Trusted_Connection=True;TrustServerCertificate=True;");
        }

        //Adding Domain Classes as DbSet Properties
        public DbSet<Employee> Employees { get; set; }

    }
}
Generate the Migration and Update the Database:

Open Package Manager Console and Execute the following add-migration and update-database commands. You can give any name to your migration. Here, I am giving Mig1. The name that you are giving it should not be given earlier.

Generate the Migration and Update the Database

This should generate the EmployeeDB with the Employees database table with the following structure in the SQL Server database:

Generate the Migration and Update the Database

Creating the Controller:

Add a new controller named EmployeeController within the Controllers folder, and then copy and paste the following code. Here, we have created the methods to perform the CRUD Operations on the Employees database table. Further, you can see we are returning JSON Data from the action methods.

using CRUDUsingQueryAJAX.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;

namespace CRUDUsingQueryAJAX.Controllers
{
    public class EmployeeController : Controller
    {
        private readonly EmployeeDBContext _context;

        public EmployeeController(EmployeeDBContext context)
        {
            _context = context;
        }

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

        [HttpGet]
        public async Task<IActionResult> GetAll()
        {
            var employees = await _context.Employees.ToListAsync();
            
            if (employees != null)
            {
                return Json(new { data = employees });
            }
            return Json(new { success = false });
        }

        [HttpGet]
        public async Task<IActionResult> GetById(int Id)
        {
            var employee = await _context.Employees.FindAsync(Id);
            if(employee != null)
            {
                return Json(new { data = employee });
            }
            return Json(new { success = false });
        }

        [HttpPost]
        public async Task<IActionResult> AddEmployee([FromBody] Employee employee)
        {
            if (ModelState.IsValid)
            {
                _context.Add(employee);
                await _context.SaveChangesAsync();
                return Json(new { success = true });
            }
            return Json(new { success = false });
        }

        [HttpPost]
        public async Task<IActionResult> UpdateEmployee([FromBody] Employee employee)
        {
            var emp = await _context.Employees.FindAsync(employee.Id);
            if (emp == null)
            {
                return Json(new { success = false });
            }

            if (ModelState.IsValid)
            {
                emp.Salary = employee.Salary;
                emp.Department = employee.Department;
                emp.Name = employee.Name;
                // _context.Update(emp);
                await _context.SaveChangesAsync();

                return Json(new { success = true });
            }

            return Json(new { success = false });
        }

        [HttpPost]
        public async Task<IActionResult> DeleteEmployee(int Id)
        {
            var employee = await _context.Employees.FindAsync(Id);
            if (employee == null)
            {
                return Json(new { success = false });
            }

            _context.Employees.Remove(employee);
            await _context.SaveChangesAsync();
            return Json(new { success = true });
        }
    }
}
Configuring the DbContext Service:

As we are using the EmployeeDBContext service in our controller, in order to inject the EmployeeDBContext instance by the MVC Framework, we need to register the EmployeeDBContext service to the built-in dependency injection container. So, add the following statement within the Program.cs class file:

SPONSOR AD

builder.Services.AddDbContext<EmployeeDBContext>();

Default Behavior for JSON Serialization:

In ASP.NET Core, the default behavior for JSON serialization is to use camelCase naming. This means property names like FirstName in your C# model are automatically converted to firstName in the JSON output. Similarly, the property name Department will automatically convert to department. We need to configure the JSON serializer options if you want to keep the property names exactly as they are in our C# models (i.e., without converting them to camelCase). So, update the AddControllersWithViews service as follows:

builder.Services.AddControllersWithViews()
.AddJsonOptions(options =>
{
    // A property naming policy, or null to leave property names unchanged.
    options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
Client-Side Libraries:

We must refer to the proper client-side libraries as we will use jQuery AJAX and Bootstrap Modal popup in our application. We need to refer to the following client-side libraries in the following sequence; otherwise, it might not work as expected.

<!-- jQuery (necessary for Bootstrap's JavaScript plugins and AJAX) -->

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Bootstrap CSS -->

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<!-- Bootstrap JS -->

<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>
Creating Index View:

Now, we will create the Index view to perform the CRUD operations using jQuery AJAX. So, add a view named Index.cshtml within the Views/Employee folder and then copy and paste the following code.

@{
    ViewData["Title"] = "Index";
}

<p class="container">
    <h2>Employees Record</h2>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" onclick="clearTextBox();">
        Add New Employee
    </button><br /><br />
    <table class="table table-bordered table-hover">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>Salary</th>
                <th>Department</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody class="tbody">
            <!-- Employee records will be populated here -->
        </tbody>
    </table>
</p>

<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabelAddEmployee" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabelAddEmployee">Add Employee</h4>
                <h4 class="modal-title" style="display:none;" id="myModalLabelUpdateEmployee">Update Employee</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>

            <div class="modal-body">
                <form>
                    <input type="hidden" id="Id" name="Id" />
                    <div class="form-group">
                        <label for="Name">Name</label>
                        <input type="text" class="form-control" id="Name" placeholder="Name" />
                    </div>
                    <div class="form-group">
                        <label for="Salary">Salary</label>
                        <input type="text" class="form-control" id="Salary" placeholder="Salary" />
                    </div>
                    <div class="form-group">
                        <label for="Department">Department</label>
                        <input type="text" class="form-control" id="Department" placeholder="Department" />
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-primary" id="btnAdd" onclick="return Add();">Add Employee</button>
                <button type="button" class="btn btn-primary" id="btnUpdate" style="display:none;" onclick="return Update();">Update</button>
                <button type="button" class="btn btn-danger" data-dismiss="modal">Close</button>
            </div>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteConfirmationModal" tabindex="-1" role="dialog" aria-labelledby="deleteModalLabel" aria-hidden="true">
    <div class="modal-dialog" role="document">
        <div class="modal-content">
            <div class="modal-header">
                Are you sure you want to delete the following Employee?
            </div>
            <div class="modal-body">
                <input type="hidden" id="HiddenEmployeeId" name="HiddenEmployeeId" />
                <label id="labelToUpdateName" style="display: block; text-align: center;"></label><br />
                <label id="labelToUpdateDepartment" style="display: block; text-align: center;"></label><br />
                <label id="labelToUpdateSalary" style="display: block; text-align: center;"></label><br />
            </div>

            <div class="modal-footer">
                <button type="button" class="btn btn-danger" id="btnDelete" onclick="return Delete();">Delete</button>
                <button type="button" class="btn btn-primary" data-dismiss="modal">Cancel</button>
            </div>
        </div>
    </div>
</div>

<!-- jQuery (necessary for Bootstrap's JavaScript plugins and AJAX) -->
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<!-- Bootstrap JS -->
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.bundle.min.js"></script>

<script>
    // Load Data in Table when document is ready
    $(document).ready(function () {
        loadData();
    });

    // Load Data function
    function loadData() {
        $.ajax({
            url: '/Employee/GetAll',
            type: 'GET',
            success: function (result) {
                var html = '';
                $.each(result.data, function (key, item) {
                    html += '<tr>';
                    html += '<td>' + item.Id + '</td>';
                    html += '<td>' + item.Name + '</td>';
                    html += '<td>' + item.Salary + '</td>';
                    html += '<td>' + item.Department + '</td>';
                    html += '<td><a href="#" class="btn btn-primary" onclick="return getbyID(' + item.Id + ')">Edit</a>  <a href="#" class="btn btn-danger" onclick="ConfirmDelete(' + item.Id + ')">Delete</a></td>';
                    html += '</tr>';
                });
                $('.tbody').html(html);
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    }

    // Add Employee Data Function
    function Add() {

        var employee = {
            EmployeeID: $('#Id').val(),
            Name: $('#Name').val(),
            Salary: $('#Salary').val(),
            Department: $('#Department').val()
        };
        $.ajax({
            url: '@Url.Action("AddEmployee", "Employee")',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(employee),
            success: function (result) {
                loadData();
                $('#myModal').modal('hide');
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    }

    // Function for getting the Data Based upon Employee ID
    function getbyID(EmpID) {
        $('#Name').css('border-color', 'lightgrey');
        $('#Salary').css('border-color', 'lightgrey');
        $('#Department').css('border-color', 'lightgrey');
        $.ajax({
            url: "/Employee/GetById/" + EmpID,
            type: "GET",
            contentType: 'application/json',
            success: function (result) {

                $('#Id').val(result.data.Id);
                $('#Name').val(result.data.Name);
                $('#Salary').val(result.data.Salary);
                $('#Department').val(result.data.Department);

                $('#myModal').modal('show');
                $('#btnUpdate').show();
                $('#btnAdd').hide();
                $('#myModalLabelAddEmployee').hide();
                $('#myModalLabelUpdateEmployee').show();
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
        return false;
    }

    // Function for updating employee's record
    function Update() {

        var employee = {
            Id: $('#Id').val(),
            Name: $('#Name').val(),
            Salary: $('#Salary').val(),
            Department: $('#Department').val(),
        };
        $.ajax({
            url: '@Url.Action("UpdateEmployee", "Employee")',
            type: 'POST',
            contentType: 'application/json',
            data: JSON.stringify(employee),
            success: function (result) {
                loadData();
                $('#myModal').modal('hide');
                $('#Id').val("");
                $('#Name').val("");
                $('#Salary').val("");
                $('#Department').val("");
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    }

    // Function for showing the Popup before deletion
    function ConfirmDelete(EmpID) {

        $.ajax({
            url: "/Employee/GetById/" + EmpID,
            type: "GET",
            contentType: 'application/json',
            success: function (result) {
                $("#labelToUpdateName").html("<b>Name: </b>" + result.data.Name);
                $("#labelToUpdateDepartment").html("<b>Department: </b>" + result.data.Department);
                $("#labelToUpdateSalary").html("<b>Salary: </b>" + result.data.Salary);

                $('#HiddenEmployeeId').val(EmpID);
                $('#deleteConfirmationModal').modal('show');
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    }

    // Function for deleting the Employee
    function Delete() {

        var ID = $('#HiddenEmployeeId').val();

        $.ajax({
            url: "/Employee/DeleteEmployee/" + ID,
            type: 'POST',
            contentType: 'application/json',
            success: function (result) {
                loadData();
                $('#deleteConfirmationModal').modal('hide');
            },
            error: function (errormessage) {
                alert(errormessage.responseText);
            }
        });
    }

    // Function for clearing the textboxes
    function clearTextBox() {
        $('#Id').val("");
        $('#Name').val("");
        $('#Salary').val("");
        $('#Department').val("");
        $('#btnUpdate').hide();
        $('#btnAdd').show();
        $('#Name').css('border-color', 'lightgrey');
        $('#Salary').css('border-color', 'lightgrey');
        $('#Department').css('border-color', 'lightgrey');
    }
</script>

Now, save the changes, run the application, navigate to the Employee/Index URL, and check the functionality. It should work as expected.

In the next article, I will discuss How to Implement the Cascading Dropdown List in ASP.NET Core MVC using jQuery AJAX with an Example. In this article, I explain How to Perform CRUD Operation on a Single Page in ASP.NET Core MVC using jQuery Ajax with an Example. I hope you enjoy this article, CRUD Operation on a Single Page in ASP.NET Core MVC using jQuery Ajax.

SPONSOR AD

Leave a Reply

Your email address will not be published. Required fields are marked *