Please enable Javascript to correctly display the contents on Dot Net Tricks!

CRUD Operations using jQuery dialog, Entity Framework and ASP.NET MVC

Posted By : Shailendra Chauhan, 17 Nov 2012
Updated On : 11 Jun 2014
Total Views : 191,595   
Support : MVC5, MVC4 & MVC3
 

This article will demonstrate, how to create an Asp.Net MVC application with CRUD (Create, Read, Update, Delete) Operations using jQuery and Entity Framework code first. suppose you have following data model and DataContext classes in EF.

 public class User
 {
 public int UserID { get; set; }
 [Required(ErrorMessage = "Please Enter Your Name")]
 public string Name { get; set; }
 [Required(ErrorMessage = "Please Enter Your Address")]
 public string Address { get; set; }
 [Required(ErrorMessage = "Please Enter Your Contact No")]
 public string ContactNo { get; set; }
 }

public class DataContext : DbContext
 {
 public DataContext()
 : base("DefaultConnection")
 {

 }

 public DbSet<User> Users { get; set; }
 }

Now migrate your data model class into SQL Server database by using EF code first database migration. For more help refer this link Understanding Entity Framework Code First Migrations

Create Operation

Read Operation

Update Operation

Delete Operation

Making jQuery dialogs for CRUD Operations

 @model IEnumerable<jQuery_CRUD.DAL.User>
@{
 ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery-1.8.2.min.js"></script>
<script src="~/Scripts/jquery-ui-1.8.24.min.js"></script>
<link href="~/Content/themes/base/jquery-ui.css" rel="stylesheet" />
<script>
 $(document).ready(function () {
 var url = "";
 $("#dialog-alert").dialog({
 autoOpen: false,
 resizable: false,
 height: 170,
 width: 350,
 show: { effect: 'drop', direction: "up" },
 modal: true,
 draggable: true,
 open: function (event, ui) {
 $(".ui-dialog-titlebar-close").hide();
 },
 buttons: {
 "OK": function () {
 $(this).dialog("close");

 },
 "Cancel": function () {
 $(this).dialog("close");
 }
 }
 });

 if ('@TempData["msg"]' != "") {
 $("#dialog-alert").dialog('open');
 }

 $("#dialog-edit").dialog({
 title: 'Create User',
 autoOpen: false,
 resizable: false,
 width: 400,
 show: { effect: 'drop', direction: "up" },
 modal: true,
 draggable: true,
 open: function (event, ui) {
 $(".ui-dialog-titlebar-close").hide();
 $(this).load(url);
 }
 });

 $("#dialog-confirm").dialog({
 autoOpen: false,
 resizable: false,
 height: 170,
 width: 350,
 show: { effect: 'drop', direction: "up" },
 modal: true,
 draggable: true,
 open: function (event, ui) {
 $(".ui-dialog-titlebar-close").hide();

 },
 buttons: {
 "OK": function () {
 $(this).dialog("close");
 window.location.href = url;
 },
 "Cancel": function () {
 $(this).dialog("close");
 }
 }
 });

 $("#dialog-detail").dialog({
 title: 'View User',
 autoOpen: false,
 resizable: false,
 width: 400,
 show: { effect: 'drop', direction: "up" },
 modal: true,
 draggable: true,
 open: function (event, ui) {
 $(".ui-dialog-titlebar-close").hide();
 $(this).load(url);
 },
 buttons: {
 "Close": function () {
 $(this).dialog("close");
 }
 }
 });

 $("#lnkCreate").live("click", function (e) {
 //e.preventDefault(); //use this or return false
 url = $(this).attr('href');
 $("#dialog-edit").dialog('open');

 return false;
 });

 $(".lnkEdit").live("click", function (e) {
 // e.preventDefault(); use this or return false
 url = $(this).attr('href');
 $(".ui-dialog-title").html("Update User");
 $("#dialog-edit").dialog('open');

 return false;
 });

 $(".lnkDelete").live("click", function (e) {
 // e.preventDefault(); use this or return false
 url = $(this).attr('href');
 $("#dialog-confirm").dialog('open');

 return false;
 });

 $(".lnkDetail").live("click", function (e) {
 // e.preventDefault(); use this or return false
 url = $(this).attr('href');
 $("#dialog-detail").dialog('open');

 return false;
 });

 $("#btncancel").live("click", function (e) {
 $("#dialog-edit").dialog("close");
 return false;
 });
 });
</script>
<div id="dialog-alert" style="display: none">
 <p>
 @TempData["msg"]!
 </p>
</div>

<div id="dialog-confirm" style="display: none">
 <p>
 <span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
 Are you sure to delete?
 </p>
</div>

<div id="dialog-edit" style="display: none">
</div>
<div id="dialog-detail" style="display: none">
</div>

<h2>Users List</h2>

<p>
 @Html.ActionLink("Create New", "Create", null, new { id = "lnkCreate" })
</p>
<table>
 <tr>
 <th>
 @Html.DisplayNameFor(model => model.Name)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.Address)
 </th>
 <th>
 @Html.DisplayNameFor(model => model.ContactNo)
 </th>
 <th></th>
 </tr>

 @foreach (var item in Model)
 {
 <tr>
 <td>
 @Html.DisplayFor(modelItem => item.Name)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.Address)
 </td>
 <td>
 @Html.DisplayFor(modelItem => item.ContactNo)
 </td>
 <td>
 @Html.ActionLink("Edit", "Edit", new { id = item.UserID }, new { @class = "lnkEdit" }) |
 @Html.ActionLink("Details", "Details", new { id = item.UserID }, new { @class = "lnkDetail" }) |
 @Html.ActionLink("Delete", "Delete", new { id = item.UserID }, new { @class = "lnkDelete" })
 </td>
 </tr>
 }

</table>

Controller for handling CRUD Operations

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

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

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

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

 // POST: /User/Create
 [HttpPost]
 [ValidateAntiForgeryToken]
 public ActionResult Create(User user, string Command)
 {
 if (ModelState.IsValid)
 {
 db.Users.Add(user);
 db.SaveChanges();
 TempData["Msg"] = "Data has been saved succeessfully";
 return RedirectToAction("Index");
 }

 return View(user);
 }

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

 // POST: /User/Edit/5
 [HttpPost]
 [ValidateAntiForgeryToken]
 public ActionResult Edit(User user)
 {
 if (ModelState.IsValid)
 {
 db.Entry(user).State = EntityState.Modified;
 db.SaveChanges();
 TempData["Msg"] = "Data has been updated succeessfully";
 return RedirectToAction("Index");
 }
 return View(user);
 }

 // GET: /User/Delete/5
 public ActionResult Delete(int id)
 {
 User user = db.Users.Find(id);
 db.Users.Remove(user);
 db.SaveChanges();
 TempData["Msg"] = "Data has been deleted succeessfully";
 return RedirectToAction("Index");
 }

 protected override void Dispose(bool disposing)
 {
 db.Dispose();
 base.Dispose(disposing);
 }
 }
What do you think?

I hope you will enjoy these tricks while programming with ASP.NET MVC. I would like to have feedback from my blog readers. Your valuable feedback, question, or comments about this article are always welcome.


 
Recommended for you
 
About the Author
Shailendra Chauhan

Shailendra Chauhan is an Entrepreneur, Author, Architect, and Corporate Trainer. He has rewarded as Microsoft MVP for his exceptional contributions in Microsoft Visual Studio and Development Technologies.

With more than 7 years in hand experience Shailendra Chauhan is a polymath in the domains of Microsoft .NET technologies and an array of other technologies including JavaScript, AngularJS, Node.js, Ionic and NoSQL Databases to name but a few.

He is the author of some of most popular e-books which encompass technical Interview on Node.js Interview Questions and Answers , ASP.NET MVC Interview Questions and Answers , AngularJS Interview Questions and Answers and LINQ Interview Questions and Answers. Furthermore he is a technical reviewer for book on ASP.NET MVC 4 Mobile App Development. Know more...
 
Free Interview Books
 
10 SEP
ASP.NET MVC with AngularJS Development (offline)

SAT,SUN 05:00 PM-06:30 PM IST

More Details
7 SEP
ASP.NET MVC with AngularJS Development (online)

Weekdays (Mon-Fri) 07:30 AM-09:00 AM IST

More Details
27 AUG
ASP.NET MVC with AngularJS Development (online)

Weekend (Sat, Sun) 03:00 PM-05:00 PM IST

More Details
27 AUG
PPC Marketing (offline)

Sat, Sun 03:00 PM-05:00 PM IST

More Details
26 AUG
NodeJS Development (online)

MON-FRI 06:00 AM-07:30 AM IST

More Details
20 AUG
NodeJS Development (offline)

Sat, Sun     11:00 AM-12:30 PM IST

16 AUG
NodeJS Development (online)

Mon-Fri     09:00 PM-10:30 PM IST

12 AUG
ASP.NET MVC with AngularJS Development (online)

Mon-Fri     09:30 PM-11:00 PM IST

5 AUG
AngularJS Development (online)

Mon-Fri     08:00 PM-09:30 PM IST

1 AUG
ASP.NET MVC with AngularJS Development (online)

Mon-Fri     07:30 AM-09:00 AM IST

24 JUL
AngularJS Development (offline)

Sat,Sun     08:00 AM-09:30 AM

24 JUL
ASP.NET MVC with AngularJS Development (offline)

Sat, Sun     09:30 AM-11:00 AM

14 JUL
PPC Marketing (offline)

Sat, Sun     12:00 AM-02:00 PM IST

11 MAY
.NET Development (offline)

Mon-Fri     9:00 AM-11:00 AM IST

BROWSE BY CATEGORY
 
SUBSCRIBE TO LATEST NEWS
 
LIKE US ON FACEBOOK
 
+