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.
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace EditableWebgrid.Models
- {
- public class UserModel
- {
- public int ID { get; set; }
- public string Name { get; set; }
- public string SurName { get; set; }
-
- public static List<UserModel> getUsers()
- {
- List<UserModel> users = new List<UserModel>()
- {
- new UserModel (){ ID=1, Name="Anubhav", SurName="Chaudhary" },
- new UserModel (){ ID=2, Name="Mohit", SurName="Singh" },
- new UserModel (){ ID=3, Name="Sonu", SurName="Garg" },
- new UserModel (){ ID=4, Name="Shalini", SurName="Goel" },
- new UserModel (){ ID=5, Name="James", SurName="Bond" },
- };
- return users;
- }
- }
- }
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]()
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using EditableWebgrid.Models;
-
- namespace EditableWebgrid.Controllers
- {
- public class UserController : Controller
- {
- public ActionResult Index()
- {
- List<UserModel> users = UserModel.getUsers();
- return View(users);
- }
- }
- }
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:
- @{
- var grid = new WebGrid(Model);
- }
-
- <div id="gridContent" style=" padding:20px; " >
- @grid.GetHtml(
- tableStyle: "webgrid-table",
- headerStyle: "webgrid-header",
- footerStyle: "webgrid-footer",
- alternatingRowStyle: "webgrid-alternating-row",
- selectedRowStyle: "webgrid-selected-row",
- rowStyle: "webgrid-row-style",
- mode: WebGridPagerModes.All,
- columns:
- grid.Columns(
- grid.Column("ID", format: @<text> <span class="display-mode">@item.ID </span> <label id="UserID" class="edit-mode">@item.ID</label> </text>, style: "col1Width" ),
- 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"),
- 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"),
- grid.Column("Action", format: @<text>
- <button class="edit-user display-mode" >Edit</button>
- <button class="save-user edit-mode" >Save</button>
- <button class="cancel-user edit-mode" >Cancel</button>
- </text>, style: "col3Width" , canSort: false)
- ))
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:
- <script type="text/javascript" >
- $(function () {
- $('.edit-mode').hide();
- $('.edit-user, .cancel-user').on('click', function () {
- var tr = $(this).parents('tr:first');
- tr.find('.edit-mode, .display-mode').toggle();
- });
-
- $('.save-user').on('click', function () {
- var tr = $(this).parents('tr:first');
- var Name = tr.find("#Name").val();
- var SurName = tr.find("#SurName").val();
- var UserID = tr.find("#UserID").html();
- tr.find("#lblName").text(Name);
- tr.find("#lblSurName").text(SurName);
- tr.find('.edit-mode, .display-mode').toggle();
- var UserModel =
- {
- "ID": UserID,
- "Name": Name,
- "SurName": SurName
- };
- $.ajax({
- url: '/User/ChangeUser/',
- data: JSON.stringify(UserModel),
- type: 'POST',
- contentType: 'application/json; charset=utf-8',
- success: function (data) {
- alert(data);
- }
- });
-
- });
- })
- </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:
- sing System.Collections.Generic;
- using System.Linq;
- using System.Web;
- using System.Web.Mvc;
- using EditableWebgrid.Models;
-
- namespace EditableWebgrid.Controllers
- {
- public class UserController : Controller
- {
- public ActionResult Index()
- {
- List<UserModel> users = UserModel.getUsers();
- return View(users);
- }
-
- public JsonResult ChangeUser(UserModel model)
- {
-
- string message = "Success";
- return Json(message, JsonRequestBehavior.AllowGet);
- }
-
- }
- }
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]()