23
NovEnhancing WebGrid with Insert Update and Delete Operations
WebGrid: An Overview
Many developers want to do Insert, Update, and Delete within WebGrid like GridView but don't know how to do it. This article will help you to do the CRUD operations within WebGrid. In this MVC Tutorial, we will explore more about Insert Update and Delete Operations which include crud operations within in web grid, and grid view like insert update and delete in the web grid using jQuery.
Populating WebGrid
The Model
First of all design the customer model using the Entity Framework database first approach as shown below
div class="pre-code-wrapper"> 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 the 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, questions, or comments about this article are always welcome. Also, Consider our ASP.NET MVC Course for a better understanding of all MVC concepts.
FAQs
- Open Visual Studio.
- Run all the Database scripts in your SQL Server.
- In your ASP.Net open the "Web.
- Run the program.