ASP.NET MVC

CRUD Operations Using AJAX In ASP.NET MVC

In this article, we will learn about how we can perform crud operations using ASP.NET MVC, Ajax, Bootstrap, and jQuery. We can create the user interactive pages using Ajax.

What is AJAX?

AJAX stands for (Asynchronous JavaScript and XML) and is used to update parts of the existing page and to retrieve the data from the server.

Bootstrap is one of the most popular HTML, CSS, and JS frameworks for developing responsive, mobile first projects on the web. You can learn Bootstrap easily as it provides the classes built-in which we have to use in our application.

We are going to use code first approach for this application. If you have not idea about code first approach then you can refer our article from here

Create a new project and select the MVC pattern.

Firstly install the Entity framework from the Package manager Console

Install-Package EntityFramework

Let’s get started.

Navigate to Models -> create a new class as Users.

using System.ComponentModel.DataAnnotations;

namespace AjaxCrudOperationUsingMVC5.Models
{
    public class Users
    {
        [Key]
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string State { get; set; }
        public string Country { get; set; }
    }
}

Create the Context.cs file in the Models folder only.

using System.Data.Entity;

namespace AjaxCrudOperationUsingMVC5.Models
{
    public class Context:DbContext
    {
        public Context() : base("StringDBContext"){}
        public DbSet<Users> User { get; set; }
    }
}

Open the Web.Config file presents at the root directory and add the connection string in it.

<connectionStrings>
  <add name="StringDBContext" connectionString="Server=DESKTOP-CGB025P;Initial Catalog=DemoDB;Persist Security Info=False;User ID=sa;Password=******;MultipleActiveResultSets=True;Encrypt=False;TrustServerCertificate=False;Connection Timeout=30;" providerName="System.Data.SqlClient" />
</connectionStrings>

Open the package manager console and type the following commands.

Enable-Migrations
Add-Migration Initial
Update-Database

Open the View -> Shared -> _Layout.cshtml

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>@ViewBag.Title - My ASP.NET Application</title>
    @Styles.Render("~/Content/css")
    @Scripts.Render("~/bundles/modernizr")
    @Scripts.Render("~/bundles/jquery")
    @Scripts.Render("~/bundles/bootstrap")
</head>
<body>
    <div class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <div class="navbar-header">
                <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                    <span class="icon-bar"></span>
                </button>
                @Html.ActionLink("Ajax Crud Operations", "Index", "Home", new { area = "" }, new { @class = "navbar-brand" })
            </div>
            <div class="navbar-collapse collapse">
                <ul class="nav navbar-nav">
                    <li>@Html.ActionLink("Home", "Index", "Home")</li>
                </ul>
            </div>
        </div>
    </div>
    <div class="container body-content">
        @RenderBody()
        <hr />
        <footer>
            <p>&copy; @DateTime.Now.Year - My ASP.NET Application</p>
        </footer>
    </div>

    @RenderSection("scripts", required: false)
</body>
</html>

Open the View -> Home -> Index.cshtml file and add the code in it.

@{
    ViewBag.Title = "Home Page";
}

<div class="container">
    <h2>Users Record</h2>
    <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#myModal" >

Create the Users.js file the Script folder.

$(document).ready(function () {
    loadData();
});
function loadData() {
    $.ajax({
        url: "/Home/List",
        type: "GET",
        contentType: "application/json;charset=utf-8",
        dataType: "json",
        success: function (result) {
            var html = '';
            $.each(result, function (key, item) {
                html += '<tr>';
                html += '<td>' + item.Id + '</td>';
                html += '<td>' + item.Name + '</td>';
                html += '<td>' + item.Age + '</td>';
                html += '<td>' + item.State + '</td>';
                html += '<td>' + item.Country + '</td>';
                html += '<td><a href="#" >

Finally, open the HomeController and add the code in it.

using AjaxCrudOperationUsingMVC5.Models;
using System.Linq;
using System.Web.Mvc;

namespace AjaxCrudOperationUsingMVC5.Controllers
{
    public class HomeController : Controller
    {
        private Context _context;
        public HomeController()
        {
            _context = new Context();
        }
        public ActionResult Index()
        {
            return View();
        }
        public JsonResult List()
        {
            return Json(_context.User.ToList(), JsonRequestBehavior.AllowGet);
        }
        public JsonResult Add(Users user)
        {
            _context.User.Add(user);
            _context.SaveChanges();
            return Json(JsonRequestBehavior.AllowGet);
        }
        public JsonResult GetbyID(int ID)
        {
            return Json(_context.User.FirstOrDefault(x=>x.Id==ID), JsonRequestBehavior.AllowGet);
        }
        public JsonResult Update(Users user)
        {
            var data = _context.User.FirstOrDefault(x => x.Id == user.Id);
            if (data != null) {
                data.Name = user.Name;
                data.State = user.State;
                data.Country = user.Country;
                data.Age = user.Age;
                _context.SaveChanges();
            }
            return Json(JsonRequestBehavior.AllowGet);
        }
        public JsonResult Delete(int ID)
        {
            var data = _context.User.FirstOrDefault(x => x.Id == ID);
            _context.User.Remove(data);
            _context.SaveChanges();
            return Json(JsonRequestBehavior.AllowGet);
        }
    }
}

That’s it.

Output:

You can download the source code from here

Vision Infotech is a well-known tech firm established in Surat, India. It provides a wide range of services for mobile and web app development. It employs 250 people who specialize in website and app development. When you hire Experienced .Net developers, you can benefit from their experience in a variety of industries as well as their understanding of the most up-to-date technologies and frameworks.

Faisal Pathan

Faisal Pathan is a founder of TheCodeHubs, .NET Project Manager/Team Leader, and C# Corner MVP. He has extensive experience with designing and developing enterprise-scale applications. He has good skills in ASP.NET C#, ASP.NET Core, ASP.NET MVC, AngularJS, Angular, React, NodeJS, Amazon S3, Web API, EPPlus, Amazon MWS, eBay Integration, SQL, Entity Framework, JavaScript, eCommerce Integration like Walmart, Tanga, Newegg, Group-on Store, etc. and Windows services.

View Comments

Share
Published by
Faisal Pathan

Recent Posts

Testing hk

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Operation

Testing

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

Create and Used PIPE in angular

In this article, we have to show Create and Used PIPE in angular

2 years ago

TETS NEW

test

2 years ago