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

Enhancing WebGrid with Insert Update and Delete Operations

Posted By : Shailendra Chauhan, 15 Jan 2013
Updated On : 11 Jun 2014
Total Views : 158,642   
Support : MVC4 & MVC3
 

Many developers want to do Insert, Update and Delete with in WebGrid like as GridView, but don't know how to do it. This article will help you to do the CRUD operations with in WebGrid.

Populating WebGrid

The Model

First of all design the customer model using Entity Framework database first approach as show below

CREATE TABLE [dbo].[Customer]
(
 [CustID] [int] IDENTITY(1,1) PRIMARY KEY,
 [Name] [varchar](100) NULL,
 [Address] [varchar](200) NULL,
 [ContactNo] [varchar](20) NULL,
)

Now design the model for querying the data from customer table and populating it to the GridView

public static class SortExtension
{
 public static IOrderedEnumerable OrderByWithDirection
 (this IEnumerable source,Func keySelector,bool descending)
 {
 return descending ? source.OrderByDescending(keySelector)
 : source.OrderBy(keySelector);
 }
 
 public static IOrderedQueryable OrderByWithDirection
 (this IQueryable source,Expression> keySelector,
 bool descending)
 {
 return descending ? source.OrderByDescending(keySelector)
 : source.OrderBy(keySelector);
 }
}

public class ModelServices : IDisposable
{
 private readonly TestDBEntities entities = new TestDBEntities();
 
 public IEnumerable<Customer> GetCustomerPage(int pageNumber, int pageSize, string sort, bool Dir)
 {
 if (pageNumber < 1)
 pageNumber = 1;
 
 if (sort == "name")
 return entities.Customers.OrderByWithDirection(x => x.Name, Dir)
 .Skip((pageNumber - 1) * pageSize)
 .Take(pageSize)
 .ToList();
 else if (sort == "address")
 return entities.Customers.OrderByWithDirection(x => x.Address, Dir)
 .Skip((pageNumber - 1) * pageSize)
 .Take(pageSize)
 .ToList();
 else if (sort == "contactno")
 return entities.Customers.OrderByWithDirection(x => x.ContactNo, Dir)
 .Skip((pageNumber - 1) * pageSize)
 .Take(pageSize)
 .ToList();
 else
 return entities.Customers.OrderByWithDirection(x => x.CustID, Dir)
 .Skip((pageNumber - 1) * pageSize)
 .Take(pageSize)
 .ToList();
 }
 public int CountCustomer()
 {
 return entities.Customers.Count();
 }
 
 public void Dispose()
 {
 entities.Dispose();
 }
}

public class PagedCustomerModel
{
 public int TotalRows { get; set; }
 public IEnumerable<Customer> Customer { get; set; }
 public int PageSize { get; set; }
}

The View

Now design the view based on the above developed model as show below

@model Mvc4_WebGrid_CRUD.Models.PagedCustomerModel
@{
 ViewBag.Title = "WebGrid CRUD Operations";
 WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);
 grid.Bind(Model.Customer,autoSortAndPage: false,rowCount: Model.TotalRows
 ); 
}

<div id="divmsg" style="color: green; font-weight: bold"></div>
<a href="#" class="add">Add New</a>
<br />
<br />
@grid.GetHtml(
 htmlAttributes: new { id = "grid" },
 fillEmptyRows: false,
 mode: WebGridPagerModes.All,
 firstText: "<< First",
 previousText: "< Prev",
 nextText: "Next >",
 lastText: "Last >>",
 columns: new[] {
 grid.Column("CustID",header: "ID", canSort: false),
 
 grid.Column(header: "Name",format: @<span> <span id="spanName_@item.CustID">@item.Name</span> @Html.TextBox("Name_"+(int)item.CustID,(string)item.Name,new{@style="display:none"})</span>),
 
 grid.Column(header: "Address",format: @<span> <span id="spanAddress_@item.CustID">@item.Address</span> @Html.TextBox("Address_"+(int)item.CustID,(string)item.Address,new{@style="display:none"})</span>),
 
 grid.Column(header: "Contact No",format: @<span> <span id="spanContactNo_@item.CustID">@item.ContactNo</span> @Html.TextBox("ContactNo_"+(int)item.CustID,(string)item.ContactNo,new{@style="display:none"})</span>),
 
 grid.Column(header: "Action",format:@<text> <a href="#" id="Edit_@item.CustID" class="edit">Edit</a><a href="#" id="Update_@item.CustID" style="display:none" class="update">Update</a><a href="#" id="Cancel_@item.CustID" style="display:none" class="cancel">Cancel</a><a href="#" id="Delete_@item.CustID" class="delete">Delete</a></text>)
})

The Controller

Now, let's see how to write the code for populating the webgrid using model class and methods.

public class HomeController : Controller
{
 ModelServices mobjModel = new ModelServices();
 
 public ActionResult WebGridCRUD(int page = 1, string sort = "custid", string sortDir = "ASC")
 {
 const int pageSize = 10;
 var totalRows = mobjModel.CountCustomer();
 
 bool Dir = sortDir.Equals("desc", StringComparison.CurrentCultureIgnoreCase) ? true : false;
 
 var customer = mobjModel.GetCustomerPage(page, pageSize, sort, Dir);
 var data = new PagedCustomerModel()
 {
 TotalRows = totalRows,
 PageSize = pageSize,
 Customer = customer
 };
 return View(data);
 }
}

Insert Operation

The Model

public bool SaveCustomer(string name, string address, string contactno)
{
 try
 {
 Customer cust = new Customer();
 cust.Name = name;
 cust.Address = address;
 cust.ContactNo = contactno;
 
 entities.Customers.Add(cust);
 entities.SaveChanges();
 return true;
 }
 catch
 {
 return false;
 }
}

The View

<script type="text/javascript">
$(".add").live("click", function () {
 
 var existrow = $('.save').length;
 if (existrow == 0) {
 var index = $("#grid tbody tr").length + 1;
 
 var Name = "Name_" + index;
 var Address = "Address_" + index;
 var ContactNo = "ContactNo_" + index;
 var Save = "Save_" + index;
 var Cancel = "Cancel_" + index;
 
 var tr = '<tr class="alternate-row"><td></td><td><span> <input id="' + Name + '" type="text" /></span></td>' +
 '<td><span> <input id="' + Address + '" type="text" /></span></td>' +
 '<td><span> <input id="' + ContactNo + '" type="text" /></span></td>' +
 '<td> <a href="#" id="' + Save + '" class="save">Save</a><a href="#" id="' + Cancel + '" class="icancel">Cancel</a></td>' +
 '</tr>';
 
 $("#grid tbody").append(tr);
 }
 else {
 alert('First Save your previous record !!');
 }
 
 });
 
$(".icancel").live("click", function () {
 var flag = confirm('Are you sure to cancel');
 if (flag) {
 $(this).parents("tr").remove();
 }
});
 
$(".save").live("click", function () {
 var id = $("#grid tbody tr").length;
 var Name = $("#Name_" + id).val();
 var Address = $("#Address_" + id).val();
 var ContactNo = $("#ContactNo_" + id).val();
 
 if (id != "") {
 $.ajax({
 type: "GET",
 contentType: "application/json; charset=utf-8",
 url: '@Url.Action("SaveRecord", "Home")',
 data: { "name": Name, "address": Address, "contactno": ContactNo },
 dataType: "json",
 beforeSend: function () { },
 success: function (data) {
 if (data.result == true) {
 $("#divmsg").html("Record has been saved successfully !!");
 setTimeout(function () { window.location.replace("WebGridCRUD"); }, 2000);
 }
 else {
 alert('There is some error');
 }
 }
 });
 }
});
<script>

The Controller

[HttpGet]
public JsonResult SaveRecord(string name, string address, string contactno)
{
 bool result = false;
 try
 {
 result = mobjModel.SaveCustomer(name, address, contactno);
 }
 catch (Exception ex)
 {
 }
 return Json(new { result }, JsonRequestBehavior.AllowGet);
}

How it works..

Update Operation

The Model

public bool UpdateCustomer(int id, string name, string address, string contactno)
{
 try
 {
 var cust = (from tbl in entities.Customers
 where tbl.CustID == id
 select tbl).FirstOrDefault();
 cust.Name = name;
 cust.Address = address;
 cust.ContactNo = contactno;
 
 entities.SaveChanges();
 return true;
 }
 catch
 {
 return false;
 }
}

The View

<script type="text/javascript">
$(".edit").live("click", function () {
 var str = $(this).attr("id").split("_");
 id = str[1];
 
 var Name = "#Name_" + id;
 var spanName = "#spanName_" + id;
 var Address = "#Address_" + id;
 var spanAddress = "#spanAddress_" + id;
 var ContactNo = "#ContactNo_" + id;
 var spanContactNo = "#spanContactNo_" + id;
 
 $(Name).show();
 $(spanName).hide();
 $(Address).show();
 $(spanAddress).hide();
 $(ContactNo).show();
 $(spanContactNo).hide();
 
 $(this).hide();
 $("#Update_" + id).show();
 $("#Cancel_" + id).show();
});

$(".update").live("click", function () {
 var str = $(this).attr("id").split("_");
 id = str[1];
 
 var Name = $("#Name_" + id).val();
 var spanName = $("#spanName_" + id).val();
 var Address = $("#Address_" + id).val();
 var spanAddress = $("#spanAddress_" + id).val();
 var ContactNo = $("#ContactNo_" + id).val();
 var spanContactNo = $("#spanContactNo_" + id).val();
 
 if (id != "") {
 $.ajax({
 type: "GET",
 contentType: "application/json; charset=utf-8",
 url: '@Url.Action("UpdateRecord", "Home")',
 data: { "id": id, "name": Name, "address": Address, "contactno": ContactNo },
 dataType: "json",
 beforeSend: function () {//alert(id);
 },
 success: function (data) {
 if (data.result == true) {
 $("#Update_" + id).hide();
 $("#Cancel_" + id).hide();
 $("#Edit_" + id).show();
 
 var Name = "#Name_" + id;
 var spanName = "#spanName_" + id;
 var Address = "#Address_" + id;
 var spanAddress = "#spanAddress_" + id;
 var ContactNo = "#ContactNo_" + id;
 var spanContactNo = "#spanContactNo_" + id;
 
 $(Name).hide();
 $(spanName).show();
 $(Address).hide();
 $(spanAddress).show();
 $(ContactNo).hide();
 $(spanContactNo).show();
 
 $(spanName).text($(Name).val());
 $(spanAddress).text($(Address).val());
 $(spanContactNo).text($(ContactNo).val());
 }
 else {
 alert('There is some error');
 }
 }
 });
 }
});

<script>

The Controller

[HttpGet]
public JsonResult UpdateRecord(int id, string name, string address, string contactno)
{
 bool result = false;
 try
 {
 result = mobjModel.UpdateCustomer(id, name, address, contactno);
 
 }
 catch (Exception ex)
 {
 }
 return Json(new { result }, JsonRequestBehavior.AllowGet);
}

How it works..

Delete Operation

The Model

public bool DeleteCustomer(int id)
{
 try
 {
 var cust = (from tbl in entities.Customers
 where tbl.CustID == id
 select tbl).FirstOrDefault();
 
 entities.Customers.Remove(cust);
 entities.SaveChanges();
 return true;
 }
 catch
 {
 return false;
 }
}

The View

<script type="text/javascript">
$(".delete").live("click", function () {
 var str = $(this).attr("id").split("_");
 id = str[1];
 
 var flag = confirm('Are you sure to delete ??');
 if (id != "" && flag) {
 $.ajax({
 type: "GET",
 contentType: "application/json; charset=utf-8",
 url: '@Url.Action("DeleteRecord", "Home")',
 data: { "id": id },
 dataType: "json",
 beforeSend: function () { },
 success: function (data) {
 if (data.result == true) {
 $("#Update_" + id).parents("tr").remove();
 }
 else {
 alert('There is some error');
 }
 }
 });
 }
});
<script>

The Controller

public bool DeleteCustomer(int id)
{
 try
 {
 var cust = (from tbl in entities.Customers
 where tbl.CustID == id
 select tbl).FirstOrDefault();
 
 entities.Customers.Remove(cust);
 entities.SaveChanges();
 return true;
 }
 catch
 {
 return false;
 }
}

How it works..

What do you think?

I hope you will enjoy the tricks while programming with MVC Razor. 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
 
28 AUG
NodeJS Development (offline)

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

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

Monday 09:30 PM-11:00 PM IST

More Details
4 AUG
NodeJS Development (online)

Thursday 06:00 AM-7:30 AM IST

More Details
1 AUG
AngularJS Development (online)

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

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

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

More Details
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)

28 MAY
ASP.NET MVC with AngularJS Development (offline)

Sat, Sun     (05:00 PM-07:00 PM IST)

30 APR
NodeJS Development (offline)

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

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