Create An Editable WebGrid In MVC4 To Implement CRUD Operations

Introduction

In one of my previous articles I explained How you can show your Data in Grid format using the WebGrid in MVC4.

In today's article I explain how to create an editable WebGrid in MVC4 to implement CRUD operations.

I will show you inline operations through which you will be able to Edit, Delete and Update the data in the Grid itself.

Use the following procedure to create a sample of such an interesting application.

Step 1

First of all I added a Model class in the Model folder. This can be done by right-clicking the Model folder and then selecting to Add a new class.

Editable WebGrid1.jpg

I named it "UserModel".

Editable WebGrid2.jpg

Step 2

Then I added the variables in this class and assigned some static values to these variables.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5.    
  6. namespace EditableWebgrid.Models  
  7. {  
  8.     public class UserModel  
  9.     {  
  10.         public int ID { getset; }  
  11.         public string Name { getset; }  
  12.         public string SurName { getset; }  
  13.    
  14.         public static List<UserModel> getUsers()  
  15.         {  
  16.             List<UserModel> users = new List<UserModel>()  
  17.             {  
  18.                 new UserModel (){ ID=1, Name="Anubhav", SurName="Chaudhary" },   
  19.                 new UserModel (){ ID=2, Name="Mohit", SurName="Singh" },  
  20.                 new UserModel (){ ID=3, Name="Sonu", SurName="Garg" },  
  21.                 new UserModel (){ ID=4, Name="Shalini", SurName="Goel" },  
  22.                 new UserModel (){ ID=5, Name="James", SurName="Bond" },  
  23.             };  
  24.             return users;  
  25.         }  
  26.     }  
  27. }  

Three variables are used named ID, Name and SurName, then a list is created that is applied to the UserModel class.

Step 3

Now I will add a View Class to a folder named "Home".

Editable WebGrid3.jpg

Until now I had just created the class, I will work on it later. Before that we will work on the Controller of this application.

For working on the Controller you again need to add a Controller class in the Controller Folder, I had named this class UserController.

Editable WebGrid4.jpg

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using EditableWebgrid.Models;  
  7.    
  8. namespace EditableWebgrid.Controllers  
  9. {  
  10.     public class UserController : Controller  
  11.     {  
  12.         public ActionResult Index()  
  13.         {  
  14.             List<UserModel> users = UserModel.getUsers();  
  15.             return View(users);  
  16.         }  
  17.     }  
  18. }  

In this class I created an ActionResult that should be named the same as your View file, that's why this ActionResult is named "Index" because my View File was named "Index".

Through this action the result value present in the user Model is passed to the Index Class.

Step 4

Now we can work on the Index file, here first of all a WebGrid is created:

  1. @{  
  2.     var grid = new WebGrid(Model);  
  3. }  
  4.    
  5. <div  id="gridContent" style=" padding:20px; " >  
  6. @grid.GetHtml(  
  7.         tableStyle: "webgrid-table",  
  8.         headerStyle: "webgrid-header",  
  9.         footerStyle: "webgrid-footer",  
  10.         alternatingRowStyle: "webgrid-alternating-row",  
  11.         selectedRowStyle: "webgrid-selected-row",  
  12.         rowStyle: "webgrid-row-style",  
  13.         mode: WebGridPagerModes.All,  
  14.         columns:  
  15.             grid.Columns(  
  16.              grid.Column("ID", format: @<text>  <span  class="display-mode">@item.ID </span> <label id="UserID" class="edit-mode">@item.ID</label> </text>, style: "col1Width" ),  
  17.              grid.Column("Name""Name", format: @<text>  <span  class="display-mode"> <label id="lblName"  >@item.Name</label> </span> <input type="text" id="Name" value="@item.Name" class="edit-mode" /></text>, style: "col2Width"),  
  18.              grid.Column("SurName""Sur Name", format: @<text> <span  class="display-mode"> <label id="lblSurName">@item.SurName</label> </span>  <input type="text" id="SurName" value="@item.SurName" class="edit-mode" /> </text>, style: "col2Width"),   
  19.              grid.Column("Action", format: @<text>  
  20.                                 <button class="edit-user display-mode" >Edit</button>  
  21.                                 <button class="save-user edit-mode"  >Save</button>  
  22.                                 <button class="cancel-user edit-mode" >Cancel</button>  
  23.                             </text>,  style: "col3Width" , canSort: false)  
  24.            ))  

First some CSS is applied to the WebGrid that you can find in the Downloadable Zip File present in the starting of this article.

Then I had created the columns, in the columns you can see that I had done some typical coding. That's because I will hide the Span whenever the user clicks on the Edit button and will display the TextBox so that he can enter a new Value then the update will be done that will replace the existing text with the new text.

You can simply write in this format: "grid.column("Name","Name"), this will show you the data available in the Name but can't be edited since this will be in Label or Span format and not in the TextBox.

After creating the columns I had created some buttons that will be used to Edit, Save and Cancel the Record. On these buttons jQuery is applied that will allow them to work as expected, it's script is as follows:

  1. <script type="text/javascript" >  
  2.     $(function () {  
  3.         $('.edit-mode').hide();  
  4.         $('.edit-user, .cancel-user').on('click'function () {  
  5.             var tr = $(this).parents('tr:first');  
  6.             tr.find('.edit-mode, .display-mode').toggle();  
  7.         });  
  8.    
  9.         $('.save-user').on('click'function () {  
  10.             var tr = $(this).parents('tr:first');  
  11.             var Name = tr.find("#Name").val();  
  12.             var SurName = tr.find("#SurName").val();  
  13.             var UserID = tr.find("#UserID").html();  
  14.             tr.find("#lblName").text(Name);  
  15.             tr.find("#lblSurName").text(SurName);  
  16.             tr.find('.edit-mode, .display-mode').toggle();  
  17.             var UserModel =  
  18.             {  
  19.                 "ID": UserID,  
  20.                 "Name": Name,  
  21.                 "SurName": SurName  
  22.             };  
  23.             $.ajax({  
  24.                 url: '/User/ChangeUser/',  
  25.                 data: JSON.stringify(UserModel),  
  26.                 type: 'POST',  
  27.                 contentType: 'application/json; charset=utf-8',  
  28.                 success: function (data) {  
  29.                     alert(data);  
  30.                 }  
  31.             });  
  32.    
  33.         });  
  34.     })  
  35. </script>  

Here as you can see that through Edit User the Label is changed to the TextBox and Cancel will again change the TextBox to Label.

Then an Ajax call is applied that is calling the Controller class and the Action created in that class, now you will be thinking that I had only created an Action Class named as Index!! Actually I had also created one more Action just below the Index Action result, so the complete code is as follows:

  1. sing System.Collections.Generic;  
  2. using System.Linq;  
  3. using System.Web;  
  4. using System.Web.Mvc;  
  5. using EditableWebgrid.Models;  
  6.    
  7. namespace EditableWebgrid.Controllers  
  8. {  
  9.     public class UserController : Controller  
  10.     {  
  11.         public ActionResult Index()  
  12.         {  
  13.             List<UserModel> users = UserModel.getUsers();  
  14.             return View(users);  
  15.         }  
  16.    
  17.         public JsonResult ChangeUser(UserModel model)  
  18.         {  
  19.             // Update model to your db  
  20.             string message = "Success";  
  21.             return Json(message, JsonRequestBehavior.AllowGet);  
  22.         }  
  23.    
  24.     }  
  25. }  

In this ChangeUser you need to create an object of the Model class in which changes are to be done. That's why I had created an object of UserModel as model.

Now this change the user will show a message whenever there will be a successful update in the Model Class.

Now our application is completely created and is ready to go.

Output

On running the application you will see an output like this one:

Editable WebGrid5.jpg

Now if you click on the Edit button then you will see that the labels will be converted into the TextBox and the Save and Cancel buttons will become visible.

Editable WebGrid6.jpg

If you click on the Cancel button then no update will be made but if you click on the Save button then the data will be changed.

Editable WebGrid7.jpg