So this article explains how to insert, select, update and delete with a webgrid. This explains CRUD operations step-by-step.

Step 1: Database

Create an EmployeeData table in a SQL database as in the following.

  1. Create Table EmployeeData
  2. (
  3. EmpID int identity (1,1) Primary Key,
  4. EmpName varchar(30),
  5. Contact nchar(15),
  6. EmailId nvarchar(50)
  7. )
Step 2: Create MVC application

Application Name
Figure 1: Application Name

MVC template
Figure 2: MVC template

Default URL
Figure 3: Default URL

Step 3: LINQ to SQL class

Create a LINQ to SQL class to read data from the table as in the following:

Add Linq to Sql Class
Figure 4: Add LINQ to SQL Class

After using the Server Explorer and adding an EmployeeData table in the surface area as in the following:

server explorer surface area
Figure 5: Server Explorer surface area

Add Table
Figure 6: Add Table

Now add a controller to the CRUD operations for EmployeeData.

So open the Solution Explorer and right-click on the controller folder and add a controller as in the following:

Select Controller
Figure 7: Select Controller

Add Controller Name
Figure 8: Add Controller Name

Step 4: Controller

Create a default controller that looks as in the following:
  1. namespace MVC.Controllers
  2. {
  3. public class EmployeeInfoController : Controller
  4. {
  5. public ActionResult Index()
  6. {
  7. return View();
  8. }
  9. }
  10. }
Now create a select controller, an insert controller, an edit controller and a the Delete controller as in the following:
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using MVC.Models;
  7. namespace MVC.Models
  8. {
  9. public class EmployeeInfoController : Controller
  10. {
  11. EmpDBDataContext db = new EmpDBDataContext();
  12. public ActionResult Index() //Record Select
  13. {
  14. List<EmployeeData> EmployeeDatas = db.EmployeeDatas.OrderByDescending(x => x.EmpID).ToList<EmployeeData>();
  15. return View(EmployeeDatas);
  16. }
  17. [HttpGet]
  18. public PartialViewResult Create() //Insert PartialView
  19. {
  20. return PartialView(new MVC.Models.EmployeeInfo());
  21. }
  22. [HttpPost]
  23. public JsonResult Create(MVC.EmployeeData Emp) // Record Insert
  24. {
  25. EmpDBDataContext db = new EmpDBDataContext();
  26. db.EmployeeDatas.InsertOnSubmit(Emp);
  27. db.SubmitChanges();
  28. return Json(Emp, JsonRequestBehavior.AllowGet);
  29. }
  30. [HttpGet]
  31. public PartialViewResult Edit(Int32 empid) // Update PartialView
  32. {
  33. EmpDBDataContext db = new EmpDBDataContext();
  34. EmployeeData emp = db.EmployeeDatas.Where(x => x.EmpID == empid).FirstOrDefault();
  35. EmployeeInfo empinfo = new EmployeeInfo();
  36. empinfo.EmailId = emp.EmpID.ToString();
  37. empinfo.EmpName = emp.EmpName;
  38. empinfo.Contact = emp.Contact;
  39. empinfo.EmailId = emp.EmailId;
  40. return PartialView(empinfo);
  41. }
  42. [HttpPost]
  43. public JsonResult Edit(MVC.EmployeeData employee) // Record Update
  44. {
  45. EmpDBDataContext db = new EmpDBDataContext();
  46. EmployeeData empdt = db.EmployeeDatas.Where(x => x.EmpID == employee.EmpID).FirstOrDefault();
  47. empdt.EmpName = employee.EmpName;
  48. empdt.Contact = employee.Contact;
  49. empdt.EmailId = employee.EmailId;
  50. db.SubmitChanges();
  51. return Json(empdt, JsonRequestBehavior.AllowGet);
  52. }
  53. public JsonResult Delete(Int32 empid)
  54. {
  55. EmployeeData emp = db.EmployeeDatas.Where(x => x.EmpID == empid).FirstOrDefault();
  56. db.EmployeeDatas.DeleteOnSubmit(emp);
  57. db.SubmitChanges();
  58. return Json(true, JsonRequestBehavior.AllowGet);
  59. }
  60. }
  61. }

Step 5: View

Now create a view and a partialview on a right-click corresponding to the controller as in the following:

Add view to controller

Figure 9: Add view to controller

1. Index View (select data)

Add Index view
Figure 10: Add Index view

In this figure see the view name is auto create, it's not changed. After selecting a Template and Model class as shown in the following figure.

Index code

  1. @model List<MVC.EmployeeData>
  2. @{
  3. ViewBag.Title = "Index";
  4. Layout = "~/Views/Shared/_Layout.cshtml";
  5. <style type="text/css">
  6. .grid {
  7. width: 100%;
  8. }
  9. </style>
  10. }
  11. <div style="padding:7px 0;">
  12. <input type="button" value="Add New Employee" onclick="CreateEmployee()" />
  13. </div>
  14. <div id='OpenDilog'></div>
  15. <h3>Employee Information List</h3>
  16. <div style="width:100%;">
  17. @{
  18. WebGrid grid = new WebGrid(Model);
  19. @grid.GetHtml(
  20. tableStyle: "grid",
  21. fillEmptyRows: false,
  22. mode: WebGridPagerModes.All,
  23. firstText: "<< First",
  24. previousText: "< Prev",
  25. nextText: "Next >",
  26. lastText: "Last >>",
  27. columns: new[] {
  28. grid.Column("EmpID",header: "ID"),
  29. grid.Column("EmpName",header: "Name"),
  30. grid.Column("Contact"),
  31. grid.Column("EmailId"),
  32. grid.Column("EmpID", header: "Action", canSort:false,
  33. format: @<text>
  34. @Html.Raw("<img src='/images/edit.png' title='Edit' onclick='EditEmployee(" + item.EmpID + ")' />")
  35. @Html.Raw("<img src='/images/delete.png' title='Edit' onclick='DeleteEmployee(" + item.EmpID + ")' />")
  36. </text>
  37. )
  38. })
  39. }
  40. </div>
  41. <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
  42. <link href="@Url.Content("~/jquery-ui-1.10.4/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" />
  43. <script src="@Url.Content("~/jquery-ui-1.10.4/ui/minified/jquery-ui.min.js")" type="text/javascript"></script>
  44. <script type="text/javascript">
  45. function CreateEmployee() {
  46. var div = $("#OpenDilog");
  47. div.load("/EmployeeInfo/Create", function () {
  48. div.dialog({
  49. modal: true,
  50. width: 500,
  51. height: 400,
  52. title: "Add New Employee",
  53. resizable: false
  54. });
  55. });
  56. }
  57. function EditEmployee(E_ID) {
  58. var ph = $("#OpenDilog");
  59. ph.load("/EmployeeInfo/Edit?EmpID=" + E_ID, function () {
  60. ph.dialog({
  61. modal: true,
  62. width: 500,
  63. height: 400,
  64. title: "Edit Employee",
  65. resizable: false
  66. });
  67. });
  68. }
  69. function DeleteEmployee(E_ID) {
  70. if (confirm("Are You Sure Delete Selected Employee Record No.? " + E_ID)) {
  71. var data = { 'EmpID': E_ID }
  72. $.post('/EmployeeInfo/Delete', data,
  73. function (data) {
  74. if (data == true)
  75. location = location.href;
  76. else
  77. alert("Not delete something Wrong");
  78. });
  79. }
  80. }
In this index view create a webgrid, script for a window open to insert data, an edit data and a delete dialog box.

2. Create View (Insert data)

Create a view to create a partial view .

Add Create view
Figure 11: Add Create view

This section also created a script for the model data insert into the table.

Create View Code
  1. @model MVC.Models.EmployeeInfo
  2. @using (Html.BeginForm())
  3. {
  4. @Html.ValidationSummary(true)
  5. <fieldset>
  6. <legend></legend>
  7. <div class="editor-label">
  8. Employee Name
  9. </div>
  10. <div class="editor-field">
  11. @Html.EditorFor(model => model.EmpName)
  12. @Html.ValidationMessageFor(model => model.EmpName)
  13. </div>
  14. <div class="editor-label">
  15. Contact
  16. </div>
  17. <div class="editor-field">
  18. @Html.EditorFor(model => model.Contact)
  19. @Html.ValidationMessageFor(model => model.Contact)
  20. </div>
  21. <div class="editor-label">
  22. Email ID
  23. </div>
  24. <div class="editor-field">
  25. @Html.EditorFor(model => model.EmailId)
  26. @Html.ValidationMessageFor(model => model.EmailId)
  27. </div>
  28. <p>
  29. <input type="button" value="Create" onclick="SaveEmployee()" />
  30. </p>
  31. </fieldset>
  32. }
  33. <div>
  34. @Html.ActionLink("Close", "Index")
  35. </div>
  36. <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css"/>
  37. <link href="@Url.Content("~/jquery-ui-1.10.4/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" />
  38. <script src="@Url.Content("~/jquery-ui-1.10.4/ui/minified/jquery-ui.min.js")" type="text/javascript"></script>
  39. <script type="text/javascript">
  40. function SaveEmployee() {
  41. var EmpName = $("#EmpName").val();
  42. var Contact = $("#Contact").val();
  43. var EmailId = $("#EmailId").val();
  44. var Employee = {
  45. "EmpName": EmpName, "Contact": Contact,
  46. "EmailId": EmailId
  47. };
  48. $.post("/EmployeeInfo/Create", Employee,
  49. function (data) { if (data == 0) { location = location.href; } }, 'json');
  50. }
3. Edit View (Update Employee)

Also create an Editview as a Partial view.

Add Edit View
Figure 12: Add Edit View

Edit view code
  1. @model MVC.Models.EmployeeInfo
  2. @using (Html.BeginForm())
  3. {
  4. @Html.ValidationSummary(true)
  5. <fieldset>
  6. <legend></legend>
  7. <div class="editor-label">
  8. Employee Name
  9. </div>
  10. <div class="editor-field">
  11. @Html.EditorFor(model => model.EmpName)
  12. @Html.ValidationMessageFor(model => model.EmpName)
  13. </div>
  14. <div class="editor-label">
  15. Contact
  16. </div>
  17. <div class="editor-field">
  18. @Html.EditorFor(model => model.Contact)
  19. @Html.ValidationMessageFor(model => model.Contact)
  20. </div>
  21. <div class="editor-label">
  22. Email ID
  23. </div>
  24. <div class="editor-field">
  25. @Html.EditorFor(model => model.EmailId)
  26. @Html.ValidationMessageFor(model => model.EmailId)
  27. </div>
  28. <p>
  29. <input type="button" value="Create" onclick="SaveEmployee()" />
  30. </p>
  31. </fieldset>
  32. }
  33. <div>
  34. @Html.ActionLink("Close", "Index")
  35. </div>
  36. <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css"/>
  37. <link href="@Url.Content("~/jquery-ui-1.10.4/themes/base/jquery-ui.css")" rel="stylesheet" type="text/css" />
  38. <script src="@Url.Content("~/jquery-ui-1.10.4/ui/minified/jquery-ui.min.js")" type="text/javascript"></script>
  39. <script type="text/javascript">
  40. function SaveEmployee() {
  41. var EmpName = $("#EmpName").val();
  42. var Contact = $("#Contact").val();
  43. var EmailId = $("#EmailId").val();
  44. var Employee = {
  45. "EmpName": EmpName, "Contact": Contact,
  46. "EmailId": EmailId
  47. };
  48. $.post("/EmployeeInfo/Create", Employee,
  49. function (data) { if (data == 0) { location = location.href; } }, 'json');
  50. }
  51. </script>
In this view also create an update record script as in the following.

Finally all the operation views are created and can be seen in the project solution.

Views
Figure 13: Views

Step: Models

Now create a Model for EmployeeInfo as in the following:

Add Models class
Figure 14: Add Models class

class
Figuer 15: Class Name

Models Class Code
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.ComponentModel.DataAnnotations;
  6. namespace MVC.Models
  7. {
  8. public class EmployeeInfo
  9. {
  10. public int EmpID;
  11. [Required(ErrorMessage = "Can not be blank Name")]
  12. public string EmpName { get; set; }
  13. [Required(ErrorMessage = "Can not be blank Contact")]
  14. public string Contact { get; set; }
  15. [Required(ErrorMessage = "Can not be blank Email Id")]
  16. public string EmailId { get; set; }
  17. }
  18. }
Now run your MVC example in a browser.

Run Application
Figure 16: Run Application.

Now click the Add New Employee button and insert a record as in the following:

Add Record
Figure 17: Add Record

Now delete the record without 130 with the delete button.

Record Delete
Figure 18: Record Delete

Selected Record open with edit dialog
Figure 19: Selected record opened with the Edit dialog

Press the update button and close the dialog and check the record in the webgrid.

Record Update
Figure 20: Record Update

Finally you have learned how to do Create, Retrieve, Update and Delete (CRUD) operations in MVC with jQuery JSON and LINQ to SQL classes.

Note: Please maintain your database connection for CRUD.

Have a nice Day.