MVC CRUD operations using jquery Ajax with Entity Framework

MVC CRUD operations using jQuery Ajax with Entity Framework

In this example, we will demonstrate how to perform CRUD operations using jQuery Ajax with Entity Framework in an MVC application.

1. Model

Create a model class that represents your data entity. For example, let’s say we have a “User” entity:


    public class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public string Email { get; set; }
    }
  

2. Database Context

Create a database context class that derives from “DbContext” and represents your database:


    public class MyDbContext : DbContext
    {
        public MyDbContext() : base("MyDbConnectionString")
        {
        }
        
        public DbSet Users { get; set; }
    }
  

3. Controller

Create a controller class that handles CRUD operations for the “User” entity:


    public class UserController : Controller
    {
        private MyDbContext db = new MyDbContext();

        // GET: User
        public ActionResult Index()
        {
            return View(db.Users.ToList());
        }

        // GET: User/Details/5
        public ActionResult Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            
            return View(user);
        }

        // GET: User/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: User/Create
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Create([Bind(Include = "Id,Name,Email")] User user)
        {
            if (ModelState.IsValid)
            {
                db.Users.Add(user);
                db.SaveChanges();
                return RedirectToAction("Index");
            }

            return View(user);
        }

        // GET: User/Edit/5
        public ActionResult Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            
            return View(user);
        }

        // POST: User/Edit/5
        [HttpPost]
        [ValidateAntiForgeryToken]
        public ActionResult Edit([Bind(Include = "Id,Name,Email")] User user)
        {
            if (ModelState.IsValid)
            {
                db.Entry(user).State = EntityState.Modified;
                db.SaveChanges();
                return RedirectToAction("Index");
            }
            
            return View(user);
        }

        // GET: User/Delete/5
        public ActionResult Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            
            User user = db.Users.Find(id);
            if (user == null)
            {
                return HttpNotFound();
            }
            
            return View(user);
        }

        // POST: User/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public ActionResult DeleteConfirmed(int id)
        {
            User user = db.Users.Find(id);
            db.Users.Remove(user);
            db.SaveChanges();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
  

4. View

Create view files for each action in the controller using Razor syntax. For example, the “Index.cshtml” view can be created as:


    <@model IEnumerable<User>@>
    <table>
        <tr>
            <th>Id</th>
            <th>Name</th>
            <th>Email</th>
            <th>Actions</th>
        </tr>
        @foreach (var user in Model)
        {
            <tr>
                <td>@user.Id</td>
                <td>@user.Name</td>
                <td>@user.Email</td>
                <td>
                    <a href="@Url.Action("Details", new { id = user.Id })">Details</a>
                    <a href="@Url.Action("Edit", new { id = user.Id })">Edit</a>
                    <a href="@Url.Action("Delete", new { id = user.Id })">Delete</a>
                </td>
            </tr>
        }
    </table>
    <a href="@Url.Action("Create")">Create New User</a>
  

5. jQuery Ajax

In this step, we will use jQuery Ajax to perform the CRUD operations.

Creating a new user:


    $.ajax({
        type: "POST",
        url: "/User/Create",
        data: {
            Id: 1,
            Name: "John",
            Email: "john@example.com"
        },
        success: function (data) {
            // handle success
        },
        error: function (xhr, status, error) {
            // handle error
        }
    });
  

Updating an existing user:


    $.ajax({
        type: "POST",
        url: "/User/Edit",
        data: {
            Id: 1,
            Name: "John Doe",
            Email: "john.doe@example.com"
        },
        success: function (data) {
            // handle success
        },
        error: function (xhr, status, error) {
            // handle error
        }
    });
  

Deleting a user:


    $.ajax({
        type: "POST",
        url: "/User/Delete/1",
        success: function (data) {
            // handle success
        },
        error: function (xhr, status, error) {
            // handle error
        }
    });
  

Related Post

Leave a comment