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.
- CREATE TABLE [dbo].[Customer]
- (
- [CustID] [int] IDENTITY(1,1) PRIMARY KEY,
- [Name] [varchar](100) NULL,
- [Address] [varchar](200) NULL,
- [ContactNo] [varchar](20) NULL,
- )
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
- @model Mvc4_CRUD_jQueryDialog.Models.PagedCustomerModel
- @{
- ViewBag.Title = "Web Grid";
- WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
- grid.Bind(Model.Customer, autoSortAndPage: false, rowCount: Model.TotalRows );
- }
- <link href="@Url.Content("~/Content/themes/base/minified/jquery-ui.min.css")" rel="stylesheet" type="text/css" />
- <script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")" type="text/javascript"></script>
- <script src="@Url.Content("~/Scripts/jquery-ui-1.8.20.min.js")" type="text/javascript"></script>
- <script type="text/javascript">
- $(document).ready(function () {
- $("#CreateCustomer").live("click", function (e) {
- // e.preventDefault(); use this or return false
- var url = $(this).attr('href');
- $("#dialog-edit").dialog({
- title: 'Create Customer',
- autoOpen: false,
- resizable: false,
- height: 355,
- width: 400,
- show: { effect: 'drop', direction: "up" },
- modal: true,
- draggable: true,
- open: function (event, ui) {
- $(this).load(url);
- }, close: function (event, ui) {
- $(this).dialog('close');
- }
- });
- $("#dialog-edit").dialog('open'); return false;
- });
- $(".editDialog").live("click", function (e) { // e.preventDefault(); use this or return false
- var url = $(this).attr('href');
- $("#dialog-edit").dialog({
- title: 'Edit Customer',
- autoOpen: false,
- resizable: false,
- height: 355,
- width: 400,
- show: { effect: 'drop', direction: "up" },
- modal: true,
- draggable: true,
- open: function (event, ui) {
- $(this).load(url);
- }, close: function (event, ui) {
- $(this).dialog('close');
- }
- });
- $("#dialog-edit").dialog('open');
- return false;
- });
- $(".confirmDialog").live("click", function (e) {
- // e.preventDefault(); use this or return false
- var url = $(this).attr('href');
- $("#dialog-confirm").dialog({
- autoOpen: false,
- resizable: false,
- height: 170,
- width: 350,
- show: { effect: 'drop', direction: "up" },
- modal: true,
- draggable: true,
- buttons: {
- "OK": function () {
- $(this).dialog("close");
- window.location = url;
- }, "Cancel": function () {
- $(this).dialog("close");
- } } });
- $("#dialog-confirm").dialog('open');
- return false;
- });
- $(".viewDialog").live("click", function (e) {
- // e.preventDefault(); use this or return false
- var url = $(this).attr('href');
- $("#dialog-view").dialog({
- title: 'View Customer',
- autoOpen: false,
- resizable: false,
- height: 250,
- width: 400,
- show: { effect: 'drop', direction: "up" },
- modal: true,
- draggable: true,
- open: function (event, ui) {
- $(this).load(url);
- },
- buttons: {
- "Close": function () {
- $(this).dialog("close");
- }
- },
- close: function (event, ui) {
- $(this).dialog('close'); }
- });
- $("#dialog-view").dialog('open');
- return false;
- });
- $("#btncancel").live("click", function (e) {
- // location.reload(true);
- $("#dialog-edit").dialog('close');
- }); });
- </script>
- <h2>
- CRUD Operations using jQuery dialog and WebGrid</h2>
- <br />
- <div style="color: Green; font-weight: bold">
- @TempData["msg"]
- </div>
- <br />
- @grid.GetHtml(
- fillEmptyRows: false,
- alternatingRowStyle: "alternate-row",
- headerStyle: "grid-header",
- footerStyle: "grid-footer",
- mode: WebGridPagerModes.All,
- firstText: "<< First",
- previousText: "< Prev",
- nextText: "Next >",
- lastText: "Last >>",
- columns: new[] { grid.Column("CustID", header: "ID", canSort: false),
- grid.Column("Name", header: "Name", format: @<text>
- @Html.ActionLink((string)item.Name, "View", new { id = item.CustID }, new { @class = "viewDialog" })</text> ),
- grid.Column("Address"), grid.Column("ContactNo", header: "Contact No" ), grid.Column("", header: "Actions", format: @<text>
- @Html.ActionLink("Edit", "Edit", new { id = item.CustID }, new { @class = "editDialog"/*, data_dialog_id = "edit-Dialog"*/ }) |
- @Html.ActionLink("Delete", "Delete", new { id = item.CustID }, new { @class = "confirmDialog"})
- </text>
- )
- })
- <br />
- <a id="CreateCustomer" href="..\Home\Create">Create Customer</a>
- <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-view" style="display: none">
- </div>
View Code for CRUD Operations
- public class HomeController : Controller
- {
- ModelServices mobjModel = new ModelServices();
- public ActionResult Index() {
- return View();
- }
- public ActionResult Demo()
- {
- Response.Redirect("http://www.dotnet-tricks.com/Tutorial/mvclist");
- return View();
- }
- //Bind Web Grid and also do paging
- public ActionResult WebGrid(int page = 1, string sort = "name", string sortDir = "ASC")
- {
- const int pageSize = 5;
- var totalRows = mobjModel.CountCustomer();
- sortDir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? sortDir : "asc";
- var validColumns = new[] { "custid", "name", "address", "contactno" };
- if (!validColumns.Any(c => c.Equals(sort, StringComparison.CurrentCultureIgnoreCase)))
- { sort = "custid";
- }
- var customer = mobjModel.GetCustomerPage(page, pageSize, "it." + sort + " " + sortDir);
- var data = new PagedCustomerModel() {
- TotalRows = totalRows,
- PageSize = pageSize,
- Customer = customer
- };
- return View(data);
- }
- public ActionResult Create()
- {
- if (Request.IsAjaxRequest())
- {
- ViewBag.IsUpdate = false;
- return View("_Customer");
- }
- else return View();
- }
- public ActionResult View(int id) {
- var data = mobjModel.GetCustomer(id);
- if (Request.IsAjaxRequest())
- {
- CustomerModel cust = new CustomerModel();
- cust.CustID = data.CustID;
- cust.Name = data.Name;
- cust.Address = data.Address;
- cust.ContactNo = data.ContactNo;
- return View("_ViewCustomer", cust);
- }
- else
- return View(data);
- }
- public ActionResult Edit(int id)
- {
- var data = mobjModel.GetCustomer(id);
- if (Request.IsAjaxRequest())
- {
- CustomerModel cust = new CustomerModel();
- cust.CustID = data.CustID;
- cust.Name = data.Name;
- cust.Address = data.Address;
- cust.ContactNo = data.ContactNo;
- ViewBag.IsUpdate = true;
- return View("_Customer", cust);
- }
- else
- return View(data);
- }
- public ActionResult Delete(int id)
- {
- bool check = mobjModel.DeleteCustomer(id);
- var data = mobjModel.GetCustomer();
- return RedirectToAction("WebGrid");
- }
- [HttpPost]
- public ActionResult CreateEditCustomer(CustomerModel mCust, string Command)
- {
- // Validate the model being submitted
- if (!ModelState.IsValid)
- {
- return PartialView("_Customer", mCust);
- }
- else if (Command == "Save")
- {
- Customer mobjcust = new Customer();
- mobjcust.CustID = mCust.CustID;
- mobjcust.Address = mCust.Address;
- mobjcust.ContactNo = mCust.ContactNo;
- mobjcust.Name = mCust.Name;
- bool check = mobjModel.CreateCustomer(mobjcust);
- if (check)
- {
- TempData["Msg"] = "Data has been saved succeessfully";
- ModelState.Clear();
- return RedirectToAction("WebGrid", "Home");
- }
- }
- else if (Command == "Update")
- {
- Customer mobjcust = new Customer();
- mobjcust.CustID = mCust.CustID;
- mobjcust.Address = mCust.Address;
- mobjcust.ContactNo = mCust.ContactNo;
- mobjcust.Name = mCust.Name;
- bool check = mobjModel.UpdateCustomer(mobjcust);
- if (check)
- {
- TempData["Msg"] = "Data has been updated succeessfully";
- ModelState.Clear();
- return RedirectToAction("WebGrid", "Home");
- }
- }
- return PartialView("_Customer");
- }
- }