Please enable Javascript for better experience...
Add, Update and Delete in WebGrid in MVC
By Big | Apr 30, 2014 | In Articles | Update: Feb 5, 2015 | Total Views [ 20518 ]
Taged In
(18 Like)
Rate

This article is all about, how can we make WebGrid feasible to perform add, update or delete in MVC.

Introduction

Whenever we need to display data in our application, we look for a grid control. Grid control is always effective in displaying data and performing other activities like add, update or delete. In MVC we use WebGrid for this purpose but unfortunately WebGrid don't have facility to perform add, update or delete. We need to put some effort to achieve this. Let see how can we perform add, update or delete in WebGrid.

Code

Before moving ahead to my example let me summarize the namespace which contains definition for webGrid. You can find WebGrid in

System.Web.Helpers.dll as System.Web.Helpers.WebGrid()

Now it's time to start my example. Let's start with model first.

The Model

I am creating a model for contact details and naming it as ContactDetail.cs. Let's see how my model looks. It contains basic details only. Below is my model.

namespace DotNetConceptSampleMVCWebGridExample.Model
{
    public class ContactDetail
    {
        public int ID { get;set;}
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string Country { get; set; }
        public DateTime DOB { get; set; }
        public string ContactNo { get; set; }
        public bool IsActive { get; set; }
    }
}

The View

After creating model now it's time to create a view so that I can see the output. I am naming it as Index.cshtml. In view I will use WebGrid() class. If you don't require any additional functional and just want to use webGrid to display data then below code is for you.

@model ICollection<DotNetConceptSampleMVCWebGridExample.Model.ContactDetail>
@{
    ViewBag.Title = "WebGrid in MVC-DotNetConcept.Net";
}

<h2>MVC Web Grid</h2><hr />
@{
    <div>
    <h4>Simple Web Grid</h4>
        @{
    var grid1 = new WebGrid(source: Model, ajaxUpdateContainerId: "divGrid");
    <div id="divGrid">
       @grid1.GetHtml(tableStyle:"webGrid",
       columns:grid1.Columns(
                grid1.Column("ID"),
                grid1.Column("FirstName"),
                grid1.Column("LastName"),
                grid1.Column("Country"),
                grid1.Column("ContactNo"),
                grid1.Column("DOB",format:@<text>@item.DOB.ToShortDateString()</text>)))
        </div>
         }<br /><br /></div>

But I will use this one as I want to perform CRUD operation with my grid. Let's see how it looks.

@model ICollection<DotNetConceptSampleMVCWebGridExample.Model.ContactDetail>
@{
    ViewBag.Title = "WebGrid in MVC-DotNetConcept.Net";
}


<div style="width:100%;float:left;padding-bottom:50px;">
    <h4>Web Grid with Add/Update</h4>
    <a href="javascript://" id="btnAddNew">Add New(+)</a>
       @{if (Model != null) { var grid = new WebGrid(Model, canPage: true, rowsPerPage: 50, selectionFieldName: "selectedRow", ajaxUpdateContainerId: "gridContent"); grid.Pager(WebGridPagerModes.NextPrevious);
        <div id="gridContent" class="articleHeader article_lst">


            @grid.GetHtml(tableStyle: "webGrid",
            headerStyle: "",
            alternatingRowStyle: "alt",
            selectedRowStyle: "select",
            columns: grid.Columns(
             grid.Column("",
                    style: "col1",
                    format: @<text><div style="padding-left:20px;">
            <button class="btn_grid edit-item display-mode" id="@item.ID">Edit</button>
            <button class="btn_grid display-mode delete-item" id="@item.ID">Delete</button>
            <button class="btn_grid save-item edit-mode" id="@item.ID">Save</button>
            <button class="btn_grid cancel-item edit-mode" id="@item.ID">Cancel</button>
            </div>
                    </text>),
             grid.Column("ID"),
                             grid.Column("First Name",
                    style: "col2",
                    format: @<text>
            <span id="FirstName" class="display-mode">@item.FirstName</span>
                        @Html.TextBox("FirstName-Edit", (string)item.FirstName, new { @class = "edit-mode" })
                    </text>),
            grid.Column("Last Name",
                    style: "col2",
                    format: @<text>
            <span id="LastName" class="display-mode">@item.LastName</span>
                        @Html.TextBox("LastName-Edit", (string)item.LastName, new { @class = "edit-mode" })
                    </text>),
                                 grid.Column("Country",
                    style: "col2",
                    format: @<text>
            <span id="Country" class="display-mode">@item.Country</span>
                        @Html.TextBox("Country-Edit", (string)item.Country, new { @class = "edit-mode" })
                    </text>),
                                 grid.Column("Contact No",
                    style: "col2",
                    format: @<text>
            <span id="ContactNo" class="display-mode">@item.ContactNo</span>
                        @Html.TextBox("ContactNo-Edit", (string)item.ContactNo, new { @class = "edit-mode"})
                    </text>),
              grid.Column("DOB", format: @<text>
                @{if (item.DOB != null)
{<span id="DOB" class="display-mode">@item.DOB.ToShortDateString()</span>}}
            <input id="DOB-Edit" class="edit-mode datepicker" />
                </text>),
                     grid.Column("Is Active",
                    style: "col3",
                    format: @<text>
                        @{bool isActive = Convert.ToBoolean(item.IsActive);
                        <span id="IsActive" class="display-mode">@Convert.ToBoolean(item.IsActive)</span>
                            @Html.CheckBox("IsActive-Edit", isActive, new { @class = "edit-mode" })
                        }
                    </text>)))

        </div>
}
}
</div>

The Controller

When I am done with my model and view, now it is time to add some code to make it functional. I am naming my controller as ExampleController.cs as I always do. Below is the code for controller. Here for getting data I am using simple list and storing data into session object. You can use database in your code.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using DotNetConceptSampleMVCWebGridExample.Model;

namespace DotNetConceptSampleMVCWebGridExample.Controllers
{
    public class ExampleController : Controller
    {
        public ActionResult Index()
        {
            if (Session["model"] == null)
                Session["model"] = GetContactDetails();
            var model = (List<ContactDetail>)Session["model"];
            return View(model);
        }
        public JsonResult SaveContact(ContactDetail model)
        {
            var modelList = (List<ContactDetail>)Session["model"];
            if(model.ID>0)
            {
               var index = modelList.FindIndex(x => x.ID == model.ID);
               modelList[index] = model;
            }
            else
            {
                var item = modelList.LastOrDefault();
                model.ID = item.ID + 1;
                modelList.Add(model);
            }
            Session["model"] = modelList;
            return Json(new { ID = model.ID, FirstName = model.FirstName, LastName = model.LastName, Country = model.Country, ContactNo = model.ContactNo, DOB = model.DOB, IsActive = model.IsActive });
        }
        public JsonResult DeleteContact(ContactDetail model)
        {
            var modelList = (List<ContactDetail>)Session["model"];
                var item = modelList.Find(x => x.ID == model.ID);
                modelList.Remove(item);
            Session["model"] = modelList;
            return Json(new { ID = model.ID});
        }
       

        List<ContactDetail> GetContactDetails()
        {
            List<ContactDetail> contact = new List<ContactDetail>{
                new ContactDetail{ID=1,FirstName="Doe", LastName="John", Country="United State", ContactNo="4445454590", DOB=new DateTime(1988,3,23), IsActive=true},
                new ContactDetail{ID=2,FirstName="Chang", LastName="Lee", Country="China", ContactNo="3323334433", DOB=new DateTime(1970,5,3), IsActive=true},
                new ContactDetail{ID=3,FirstName="Ajay", LastName="Kumar", Country="India", ContactNo="9723334444", DOB=new DateTime(1990,6,2), IsActive=true},
                new ContactDetail{ID=4,FirstName="Merry", LastName="John", Country="United State", ContactNo="2332456678", DOB=new DateTime(1978,1,1), IsActive=true},
                new ContactDetail{ID=5,FirstName="Kiran", LastName="Kher", Country="India", ContactNo="9999944566", DOB=new DateTime(1998,10,29), IsActive=true}
            };
            return contact;
        }
    }
}

Calling methods (Script)

It is almost done. Now I am adding some javascript code to call my controller methods from view. Just put these code below html in view.

 <script type="text/javascript">
        initialize();
        
        function initialize() {
            $(".datepicker").datepicker({ format: 'dd/mm/yyyy', autoclose: true, todayBtn: 'linked' })
            $(".datepicker").datepicker("update", new Date());
           
            $('#btnAddNew').click(function () {
               
                if ($('.add-item').length==0) {
                    
                    var newRow = $("<tr>");
                    newRow.append("<td style='padding-left:20px'><button class='btn_grid add-item edit-mode' id='0'>Add</button>&nbsp;<button class='btn_grid remove-item edit-mode' id='0'>Cancel</button> </td>");
                    newRow.append("<td>&nbsp;</td>");
                    newRow.append("<td><input type='text' id='FirstName-Add'/></td>");
                    newRow.append("<td><input type='text' id='LastName-Add'/></td>");
                    newRow.append("<td><input type='text' id='Country-Add'/></td>");
                    newRow.append("<td><input type='text' id='ContactNo-Add'/></td>");
                    newRow.append("<td><input id='DOB-Add' class='datepicker' value='asdff'/></td>");
                    newRow.append("<td><input type='checkbox' id='IsActive-Add'/></td>");
                   
                    $('#gridContent tbody:last').append(newRow);
                    $(".datepicker").datepicker({ format: 'dd/mm/yyyy', autoclose: true, todayBtn: 'linked' })
                    $(".datepicker").datepicker("update", new Date());
                    
                }
                $('.add-item').on('click', function () {
                    var tr = $(this).parents('tr:first');
                    var ID = $(this).prop('id');
                    var FirstName = tr.find('#FirstName-Add').val();
                    var LastName = tr.find('#LastName-Add').val();
                    var Country = tr.find('#Country-Add').val();
                    var ContactNo = tr.find('#ContactNo-Add').val();
                    var DOB = tr.find('#DOB-Add').val();
                    var IsActive = tr.find('#IsActive-Add').prop("checked");
                    
                    $.post(
                        '/Example/SaveContact/',
                        { ID: ID, FirstName: FirstName, LastName: LastName, Country: Country, ContactNo: ContactNo,DOB:DOB, IsActive: IsActive },
                        function (item) {
                            tr.find('#FirstName').text(item.FirstName);
                            tr.find('#LastName').text(item.LastName);
                            tr.find('#Country').text(item.Country);
                            tr.find('#ContactNo').text(item.ContactNo);
                            tr.find('#IsActive').text(item.IsActive);
                            tr.find('#DOB').text(item.DOB);
                        }, "json");
                    tr.remove();
                });
            });
                        $('.edit-mode').hide();
                       
                        $('.edit-item').on('click', function () {
                            $('.edit-mode').hide();
                            $('.delete-mode').hide();
                            $('.display-mode').show();
                            var tr = $(this).parents('tr:first');
                            tr.find('.edit-mode, .display-mode').toggle();
                        });
                        $('.cancel-item').on('click', function () {
                            var tr = $(this).parents('tr:first');
                            tr.find('.display-mode,.edit-mode').toggle();
                        });
                        $('.delete-item').on('click', function () {
                            if (confirm("Are you sure to delete this contact?")) {
                                var tr = $(this).parents('tr:first');
                                var ID = $(this).prop('id');
                                $.post(
                                    '/Example/DeleteContact/',
                                    { ID: ID },
                                    function (item) {
                                        tr.remove();
                                    }, "json");
                            }
                        });
                        
                        $('.save-item').on('click', function () {
                            var tr = $(this).parents('tr:first');
                            var ID = $(this).prop('id');
                            var FirstName = tr.find('#FirstName-Edit').val();
                            var LastName = tr.find('#LastName-Edit').val();
                            var Country = tr.find('#Country-Edit').val();
                            var ContactNo = tr.find('#ContactNo-Edit').val();
                            var DOB = tr.find('#DOB-Edit').val();
                            var IsActive = tr.find('#IsActive-Edit').prop("checked");
                            $.post(
                                '/Example/SaveContact/',
                                { ID: ID, FirstName: FirstName,LastName:LastName,Country:Country,ContactNo:ContactNo,DOB:DOB, IsActive: IsActive },
                                function (item) {
                                    tr.find('#FirstName').text(item.FirstName);
                                    tr.find('#LastName').text(item.LastName);
                                    tr.find('#Country').text(item.Country);
                                    tr.find('#ContactNo').text(item.ContactNo);
                                    tr.find('#IsActive').text(item.IsActive);
                                    tr.find('#DOB').text(item.DOB);
                                }, "json");
                            tr.find('.edit-mode, .display-mode').toggle();
                        });
                      
                    }
   </script>

After adding my code I will be able to perform add, update or delete operation in my WebGrid. Let's see one by one.

Add

Edit

Delelte

And I am done. See how easy it was. Hope it can help you. Why you are waiting now? Use this code and try yourself.

Share this

About the Author

Big
Rahul Jha (Big)
Founder, Developer dotnet-concept.com
Has working experience in different phases of Software Development Life Cycle (SDLC) in CMS, Gaming, Health Care and Financial Services domain using Agile pattern. Working experience in Design patterns, ASP.NET, MVC, Windows application, WCF, ADO.NET, SQL Server and Test Driven Development (TDD) environment with JQuery, JavaScript, N-Unit, Entity Frameworks, LINQ, Code Refactoring and Business Objects Models.

 
Please SignUp/Login to comment...

Or comment as anonymous...
* Name
* Email ID
Comment