Friday, December 28, 2012

CRUD Operations using jQuery


CRUD Operations using jQuery


This article will demonstrate, how to create an Asp.Net MVC application with CRUD (Create, Read, Update, Delete) Operations using jQuery JSON and Entity Framework 4.1. Suppose you have below table in database.
  1. CREATE TABLE [dbo].[Customer]
  2. (
  3. [CustID] [int] IDENTITY(1,1) PRIMARY KEY,
  4. [Name] [varchar](100) NULL,
  5. [Address] [varchar](200) NULL,
  6. [ContactNo] [varchar](20) NULL,
  7. )
Now add Ado.Net Entity Data Model to Model of your MVC application and genearate model from SQL Server database by adding above Customer table like as:

Create Operation

 

Read Operation

Update Operation

 

Delete Operation

 

View Code for CRUD Operations

  1. @model Mvc4_CRUD_jQueryDialog.Models.PagedCustomerModel
  2. @{
  3. ViewBag.Title = "Web Grid";
  4. WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
  5. grid.Bind(Model.Customer, autoSortAndPage: false, rowCount: Model.TotalRows );
  6. }
  7. <link href="@Url.Content("~/Content/themes/base/minified/jquery-ui.min.css")" rel="stylesheet" type="text/css" />
  8. <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
  9. <script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
  10. <script type="text/javascript">
  11. $(document).ready(function () {
  12. $("#CreateCustomer").live("click", function (e) {
  13. // e.preventDefault(); use this or return false
  14. var url = $(this).attr('href');
  15. $("#dialog-edit").dialog({
  16. title: 'Create Customer',
  17. autoOpen: false,
  18. resizable: false,
  19. height: 355,
  20. width: 400,
  21. show: { effect: 'drop', direction: "up" },
  22. modal: true,
  23. draggable: true,
  24. open: function (event, ui) {
  25. $(this).load(url);
  26. }, close: function (event, ui) {
  27. $(this).dialog('close');
  28. }
  29. });
  30. $("#dialog-edit").dialog('open'); return false;
  31. });
  32. $(".editDialog").live("click", function (e) { // e.preventDefault(); use this or return false
  33. var url = $(this).attr('href');
  34. $("#dialog-edit").dialog({
  35. title: 'Edit Customer',
  36. autoOpen: false,
  37. resizable: false,
  38. height: 355,
  39. width: 400,
  40. show: { effect: 'drop', direction: "up" },
  41. modal: true,
  42. draggable: true,
  43. open: function (event, ui) {
  44. $(this).load(url);
  45. }, close: function (event, ui) {
  46. $(this).dialog('close');
  47. }
  48. });
  49. $("#dialog-edit").dialog('open');
  50. return false;
  51. });
  52. $(".confirmDialog").live("click", function (e) {
  53. // e.preventDefault(); use this or return false
  54. var url = $(this).attr('href');
  55. $("#dialog-confirm").dialog({
  56. autoOpen: false,
  57. resizable: false,
  58. height: 170,
  59. width: 350,
  60. show: { effect: 'drop', direction: "up" },
  61. modal: true,
  62. draggable: true,
  63. buttons: {
  64. "OK": function () {
  65. $(this).dialog("close");
  66. window.location = url;
  67. }, "Cancel": function () {
  68. $(this).dialog("close");
  69. } } });
  70. $("#dialog-confirm").dialog('open');
  71. return false;
  72. });
  73. $(".viewDialog").live("click", function (e) {
  74. // e.preventDefault(); use this or return false
  75. var url = $(this).attr('href');
  76. $("#dialog-view").dialog({
  77. title: 'View Customer',
  78. autoOpen: false,
  79. resizable: false,
  80. height: 250,
  81. width: 400,
  82. show: { effect: 'drop', direction: "up" },
  83. modal: true,
  84. draggable: true,
  85. open: function (event, ui) {
  86. $(this).load(url);
  87. },
  88. buttons: {
  89. "Close": function () {
  90. $(this).dialog("close");
  91. }
  92. },
  93. close: function (event, ui) {
  94. $(this).dialog('close'); }
  95. });
  96. $("#dialog-view").dialog('open');
  97. return false;
  98. });
  99. $("#btncancel").live("click", function (e) {
  100. // location.reload(true);
  101. $("#dialog-edit").dialog('close');
  102. }); });
  103. </script>
  104. <h2>
  105. CRUD Operations using jQuery dialog and WebGrid</h2>
  106. <br />
  107. <div style="color: Green; font-weight: bold">
  108. @TempData["msg"]
  109. </div>
  110. <br />
  111. @grid.GetHtml(
  112. fillEmptyRows: false,
  113. alternatingRowStyle: "alternate-row",
  114. headerStyle: "grid-header",
  115. footerStyle: "grid-footer",
  116. mode: WebGridPagerModes.All,
  117. firstText: "<< First",
  118. previousText: "< Prev",
  119. nextText: "Next >",
  120. lastText: "Last >>",
  121. columns: new[] { grid.Column("CustID", header: "ID", canSort: false),
  122. grid.Column("Name", header: "Name", format: @<text>
  123. @Html.ActionLink((string)item.Name, "View", new { id = item.CustID }, new { @class = "viewDialog" })</text> ),
  124. grid.Column("Address"), grid.Column("ContactNo", header: "Contact No" ), grid.Column("", header: "Actions", format: @<text>
  125. @Html.ActionLink("Edit", "Edit", new { id = item.CustID }, new { @class = "editDialog"/*, data_dialog_id = "edit-Dialog"*/ }) |
  126. @Html.ActionLink("Delete", "Delete", new { id = item.CustID }, new { @class = "confirmDialog"})
  127. </text>
  128. )
  129. })
  130. <br />
  131. <a id="CreateCustomer" href="..\Home\Create">Create Customer</a>
  132. <div id="dialog-confirm" style="display: none">
  133. <p>
  134. <span class="ui-icon ui-icon-alert" style="float: left; margin: 0 7px 20px 0;"></span>
  135. Are you sure to delete ?
  136. </p>
  137. </div>
  138. <div id="dialog-edit" style="display: none">
  139. </div>
  140. <div id="dialog-view" style="display: none">
  141. </div>

View Code for CRUD Operations

  1. public class HomeController : Controller
  2. {
  3. ModelServices mobjModel = new ModelServices();
  4. public ActionResult Index() {
  5. return View();
  6. }
  7. public ActionResult Demo()
  8. {
  9. Response.Redirect("http://www.dotnet-tricks.com/Tutorial/mvclist");
  10. return View();
  11. }
  12. //Bind Web Grid and also do paging
  13. public ActionResult WebGrid(int page = 1, string sort = "name", string sortDir = "ASC")
  14. {
  15. const int pageSize = 5;
  16. var totalRows = mobjModel.CountCustomer();
  17. sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";
  18. var validColumns = new[] { "custid", "name", "address", "contactno" };
  19. if (!validColumns.Any(c => c.Equals(sort, StringComparison.CurrentCultureIgnoreCase)))
  20. { sort = "custid";
  21. }
  22. var customer = mobjModel.GetCustomerPage(page, pageSize, "it." + sort + " " + sortDir);
  23. var data = new PagedCustomerModel() {
  24. TotalRows = totalRows,
  25. PageSize = pageSize,
  26. Customer = customer
  27. };
  28. return View(data);
  29. }
  30. public ActionResult Create()
  31. {
  32. if (Request.IsAjaxRequest())
  33. {
  34. ViewBag.IsUpdate = false;
  35. return View("_Customer");
  36. }
  37. else return View();
  38. }
  39. public ActionResult View(int id) {
  40. var data = mobjModel.GetCustomer(id);
  41. if (Request.IsAjaxRequest())
  42. {
  43. CustomerModel cust = new CustomerModel();
  44. cust.CustID = data.CustID;
  45. cust.Name = data.Name;
  46. cust.Address = data.Address;
  47. cust.ContactNo = data.ContactNo;
  48. return View("_ViewCustomer", cust);
  49. }
  50. else
  51. return View(data);
  52. }
  53. public ActionResult Edit(int id)
  54. {
  55. var data = mobjModel.GetCustomer(id);
  56. if (Request.IsAjaxRequest())
  57. {
  58. CustomerModel cust = new CustomerModel();
  59. cust.CustID = data.CustID;
  60. cust.Name = data.Name;
  61. cust.Address = data.Address;
  62. cust.ContactNo = data.ContactNo;
  63. ViewBag.IsUpdate = true;
  64. return View("_Customer", cust);
  65. }
  66. else
  67. return View(data);
  68. }
  69. public ActionResult Delete(int id)
  70. {
  71. bool check = mobjModel.DeleteCustomer(id);
  72. var data = mobjModel.GetCustomer();
  73. return RedirectToAction("WebGrid");
  74. }
  75. [HttpPost]
  76. public ActionResult CreateEditCustomer(CustomerModel mCust, string Command)
  77. {
  78. // Validate the model being submitted
  79. if (!ModelState.IsValid)
  80. {
  81. return PartialView("_Customer", mCust);
  82. }
  83. else if (Command == "Save")
  84. {
  85. Customer mobjcust = new Customer();
  86. mobjcust.CustID = mCust.CustID;
  87. mobjcust.Address = mCust.Address;
  88. mobjcust.ContactNo = mCust.ContactNo;
  89. mobjcust.Name = mCust.Name;
  90. bool check = mobjModel.CreateCustomer(mobjcust);
  91. if (check)
  92. {
  93. TempData["Msg"] = "Data has been saved succeessfully";
  94. ModelState.Clear();
  95. return RedirectToAction("WebGrid", "Home");
  96. }
  97. }
  98. else if (Command == "Update")
  99. {
  100. Customer mobjcust = new Customer();
  101. mobjcust.CustID = mCust.CustID;
  102. mobjcust.Address = mCust.Address;
  103. mobjcust.ContactNo = mCust.ContactNo;
  104. mobjcust.Name = mCust.Name;
  105. bool check = mobjModel.UpdateCustomer(mobjcust);
  106. if (check)
  107. {
  108. TempData["Msg"] = "Data has been updated succeessfully";
  109. ModelState.Clear();
  110. return RedirectToAction("WebGrid", "Home");
  111. }
  112. }
  113. return PartialView("_Customer");
  114. }
  115. }

3 comments:

  1. This is a very nice article on "CRUD Operations using jQuery". I have find out some other articles link from which I have learnt "CURD operations using Ajax Model Dialog in ASP.NET MVC!". I think this is very helpful for developers like me.

    http://www.mindstick.com/Articles/279bc324-5be3-4156-a9e9-dd91c971d462/?CRUD%20operation%20using%20Modal%20d

    http://www.dotnet-tricks.com/Tutorial/mvc/42R0171112-CRUD-Operations-using-jQuery-dialog-and-Entity-Framework---MVC-Razor.html

    ReplyDelete
  2. Thank for the article sir i have taken reference of your site for jquery popup but i m finding problem that i m not getting any jquery popup as such there create and edit page are displayed as a normal page not inside the jquery popup as can u help me for this problem. thank u in advance..

    ReplyDelete
  3. hi, Friend me the source code does not work in modal validation, I closed the window and opens to add, I can explain the lines for validation, thanks

    ReplyDelete