Implement Insert, Update and Delete Functionality in the WebGrid: Part 3

Introduction

This article is the last and final part of the three-part article series "Implement Insert, Update and Delete Functionality in the WebGrid". In my previous two articles I explained how to work on the Controller and Model classes, so now we will work on the View part, in other words the design part of our application.

You can access my previous articles from here:

  1. Implement Insert, Update and Delete Functionality in the WebGrid: Part 1.
  2. Implement Insert, Update and Delete Functionality in the WebGrid: Part 2.

The View is main part of our application because here I will show how to declare a webgrid, how to bind data with it and how to apply Ajax calls so that Update, Delete and Save Record of the Controller Class can be executed.

Use the following procedure to create the complete process.

Step 1

First of all you need to add a View Class to the View folder, for this right-click on the View Folder and choose "Add a View".

crud in webgrid

Here first I added a new folder in the View folder and then added the View class in it.

Step 2

Now we will start writing our code, first of all you need to call the Model on which the WebGrid is to work, if you remember I had added a class in the Model Class of our application named "PagedStudentModel" in which the IT_Student class was called, I had called the same class there like:

  1. @model MvcApplication30.Models.PagedStudentModel  
  2. @{  
  3.     ViewBag.Title = "WebGrid CRUD Operations";  
  4.     WebGrid grid = new WebGrid(rowsPerPage: Model.PageSize);  
  5.     grid.Bind(Model.It_Student,  
  6.               autoSortAndPage: false,  
  7.               rowCount: Model.TotalRows  
  8.     );   
  9. }

After calling the Model class I had called the WebGrid, here you can see that I had bound it with the object of the IT_Student class that was created in the PagedStudentModel Class, secondly I had not allowed the sorting and paging but if you remember I had allowed the paging on ID of a student in my previous articles so sorting will be allowed on the ID of the student but not on others, the number of rows will be calculated by the Controller class and then directed to the Model class from where the View will use it.

Don't forget to call the Jquery-1.7.1.min.js in this View class:

  1. <script src="@Url.Content("~/jquery-1.7.1.min.js")" type="text/javascript"></script>  

Step 3

Now we will create the main things of this WebGrid, in other words binding the columns with various data and much more. For that you need to add this code:

  1. <div id="divmsg" style="color: green; font-weight: bold"></div>  
  2. <a href="#" class="add">Add New Student</a>  
  3. <br />  
  4. <br />  
  5. @grid.GetHtml(  
  6. htmlAttributes: new { id = "grid" },  
  7.     fillEmptyRows: false,  
  8.     mode: WebGridPagerModes.All,  
  9.     firstText: "<< First",  
  10.     previousText: "< Prev",  
  11.     nextText: "Next >",  
  12.     lastText: "Last >>",  
  13.      columns: new[] {  
  14.         grid.Column("Student_ID",   
  15.                     header: "ID", canSort: true),  
  16.         grid.Column(header: "Student_Name",format: @<span>   
  17. <span id="[email protected]_ID">@item.Student_Name</span> @Html.TextBox("Student_Name_"+(int)item.Student_ID,(string)item.Student_Name,new{@style="display:none"})</span>),  
  18.         grid.Column(header: "Branch",format: @<span>   
  19. <span id="[email protected]_ID">@item.Student_Branch</span>   
  20. @Html.TextBox("Student_Branch_"+(int)item.Student_ID,(string)item.Student_Branch,new{@style="display:none"})</span>),  
  21.         grid.Column(header: "City",format: @<span>   
  22. <span id="[email protected]_ID">@item.Student_City</span>   
  23. @Html.TextBox("Student_City_"+(int)item.Student_ID,(string)item.Student_City,new{@style="display:none"})</span>),  
  24.         grid.Column(header: "State",format: @<span>   
  25. <span id="[email protected]_ID">@item.Student_State</span>   
  26. @Html.TextBox("Student_State_"+(int)item.Student_ID,(string)item.Student_State,new{@style="display:none"})</span>),  
  27.         grid.Column(header: "Action",format:@<text>   
  28. <a href="#" id="[email protected]_ID" class="edit">Edit</a>  
  29. <a href="#" id="[email protected]_ID" style="display:none" class="update">Update</a><a href="#" id="[email protected]_ID" style="display:none"  class="cancel">Cancel</a>  
  30. <a href="#" id="[email protected]_ID"  class="delete">Delete</a></text>)  
  31. })

Here first I took a Div that will successfully add a new row of data, then a Link label is used for Textboxes in the Grid so that the user can enter values in them. In the Grid Columns I had bound the ID of the student to the first column, the Name of the student with the second column, the Branch of the student with the third column, the City with the fourth and the State with the fifth.

But you can see that after the first column I took some span and TextBoxes from the second column, these spans and Textboxes are bound to similar data but the difference is that whenever a Span is visible then at that time the TextBox will be hidden and when the TextBox is shown then the time span will be hidden.

Now if I run my code then the data available in the database will be shown in the Grid like this:

crud in webgrid

Step 4

Now we will work on the Ajax calls and JavaScript code to call the JSON result classes, switch between Span and TextBox, adding a new row on the click of an Add link, cancel the add and update of data.

Write this code just below where you added the jquery-1.7.1.min.js

  1. <script src="@Url.Content("~/jquery-1.7.1.min.js")" type="text/javascript"></script>  
  2. <script type="text/javascript">  
  3.     $(".add").live("click"function () {  
  4.         var existrow = $('.save').length;  
  5.         if (existrow == 0) {  
  6.             var index = $("#grid tbody tr").length + 1;  
  7.             var Student_Name = "Student_Name_" + index;  
  8.             var Student_Branch = "Student_Branch_" + index;  
  9.             var Student_City = "Student_City_" + index;  
  10.             var Student_State = "Student_State_" + index;  
  11.             var Save = "Save_" + index;  
  12.             var Cancel = "Cancel_" + index;  
  13.             var tr = '<tr class="alternate-row"><td></td><td><span> <input id="' + Student_Name + '" type="text" /></span></td>' +  
  14.                  '<td><span> <input id="' + Student_Branch + '" type="text" /></span></td>' +  
  15.                  '<td><span> <input id="' + Student_City + '" type="text" /></span></td>' +  
  16.                  '<td><span> <input id="' + Student_State + '" type="text" /></span></td>' +  
  17.  '<td> <a href="#" id="' + Save + '" class="save">Save</a>  
  18. <a href="#" id="' + Cancel + '"  class="icancel">Cancel</a></td>' +  
  19.              '</tr>';  
  20.             $("#grid tbody").append(tr);  
  21.         }  
  22.         else {  
  23.             alert('First Save your previous record !!');  
  24.         }  
  25.     });  
  26.     $(".icancel").live("click"function () {  
  27.         var flag = confirm('Are you sure to cancel');  
  28.         if (flag) {  
  29.             $(this).parents("tr").remove();  
  30.         }  
  31.     }); 

Here first I created the function for adding a new row, this function will count the number of rows and then add one more to the total, at this new number one TextBox will be created for each of the Name, Branch, City and State but not for the ID because as I said our Student ID should be Auto Incremented, then I created the function for canceling the add of any data, this function will simply remove the row that was currently added by the add function. Since you were adding a new row for new data it will ask you whether you are sure not to insert any other data. If yes then the function will start it's work.

crud in webgrid

Step 5

Now we will work on how to call the save class of the controller through Ajax and also how to pass data, for that you need to write the following code:

  1. $(".save").live("click"function () {  
  2.         var id = $("#grid tbody tr").length;  
  3.         var Student_Name = $("#Student_Name_" + id).val();  
  4.         var Student_Branch = $("#Student_Branch_" + id).val();  
  5.         var Student_City = $("#Student_City_" + id).val();  
  6.         var Student_State = $("Student_State_" + id).val();  
  7.         if (id != "") {  
  8.             $.ajax({  
  9.                 type: "GET",  
  10.                 contentType: "application/json; charset=utf-8",  
  11.                 url: '@Url.Action("SaveRecord", "ShowData")',  
  12.                 data: { "Student_Name": Student_Name, "Student_Branch": Student_Branch, "Student_City": Student_City, "Student_State": Student_State },  
  13.                 dataType: "json",  
  14.                 beforeSend: function () { },  
  15.                 success: function (data) {  
  16.                     if (data.result == true) {  
  17.                         $("#divmsg").html("Record has been saved successfully !!");  
  18.                         setTimeout(function () { window.location.replace("WebGridCRUD"); }, 2000);  
  19.                     }  
  20.                     else {  
  21.                         alert('There is some error');  
  22.                     }  
  23.                 }  
  24.             });  
  25.         }  
  26.     }); 

In this function we first created some variables in which the value of the textboxes are passed, then I used the Ajax call. In this we need to pass the type that can be either Get or Post, the content type and then comes the most important thing, passing the URL of the Controller Class that must be called from here, here SaveRecord is called that is available under the ShowData Controller.

The value of these variables are passed into some other variables that will be called in the Controller class, on the successful addition of data a message will be shown through the div that was created in the third step.

crud in webgrid

Step 6

Now we will work on the Edit function of our application, this function will change the Span into the TextBox, write this code for the Edit function:

  1. $(".edit").live("click"function () {  
  2.         var str = $(this).attr("id").split("_");  
  3.         id = str[1];  
  4.         var Student_Name = "#Student_Name_" + id;  
  5.         var spanStudent_Name = "#spanStudent_Name_" + id;  
  6.         var Student_Branch = "#Student_Branch_" + id;  
  7.         var spanStudent_Branch = "#spanStudent_Branch_" + id;  
  8.         var Student_City = "#Student_City_" + id;  
  9.         var spanStudent_City = "#spanStudent_City_" + id;  
  10.         var Student_State = "#Student_State_" + id;  
  11.         var spanStudent_State = "#spanStudent_State_" + id;  
  12.         $(Student_Name).show();  
  13.         $(spanStudent_Name).hide();  
  14.         $(Student_Branch).show();  
  15.         $(spanStudent_Branch).hide();  
  16.         $(Student_City).show();  
  17.         $(spanStudent_City).hide();  
  18.         $(Student_State).show();  
  19.         $(spanStudent_State).hide();  
  20.         $(this).hide();  
  21.         $("#Update_" + id).show();  
  22.         $("#Cancel_" + id).show();  
  23.     }); 

Here separate variables are created for each TextBox and for each Span, the click of Edit will show the Textboxes.

If the user clicks on the Update or Cancel button then the Textboxes will be hidden and the Span will be shown.

Step 7

Now we will create a function for updating the data, for this you need to write the following code:

  1. $(".update").live("click"function () {  
  2.         var str = $(this).attr("id").split("_");  
  3.         id = str[1];  
  4.         var Student_Name = $("#Student_Name_" + id).val();  
  5.         var spanStudent_Name = $("#spanStudent_Name_" + id).val();  
  6.         var Student_Branch = $("#Student_Branch_" + id).val();  
  7.         var spanStudent_Branch = $("#spanStudent_Branch_" + id).val();  
  8.         var Student_City = $("#Student_City_" + id).val();  
  9.         var spanStudent_City = $("#spanStudent_City_" + id).val();  
  10.         var Student_State = $("#Student_State_" + id).val();  
  11.         var spanStudent_State = $("#spanStudent_State_" + id).val();  
  12.         if (id != "") {  
  13.             $.ajax({  
  14.                 type: "GET",  
  15.                 contentType: "application/json; charset=utf-8",  
  16.                 url: '@Url.Action("UpdateRecord", "ShowData")',  
  17.                 data: { "id": id, "Student_Name": Student_Name, "Student_Branch": Student_Branch, "Student_City": Student_City, "Student_State": Student_State },  
  18.                 dataType: "json",  
  19.                 beforeSend: function () {//alert(id);  
  20.                 },  
  21.                 success: function (data) {  
  22.                     if (data.result == true) {  
  23.                         $("#Update_" + id).hide();  
  24.                         $("#Cancel_" + id).hide();  
  25.                         $("#Edit_" + id).show();  
  26.                         var Student_Name = "#Student_Name_" + id;  
  27.                         var spanStudent_Name = "#spanStudent_Name_" + id;  
  28.                         var Student_Branch = "#Student_Branch_" + id;  
  29.                         var spanStudent_Branch = "#spanStudent_Branch_" + id;  
  30.                         var Student_City = "#Student_City_" + id;  
  31.                         var spanStudent_City = "#spanStudent_City_" + id;  
  32.                         var Student_State = "#Student_State_" + id;  
  33.                         var spanStudent_State = "#spanStudent_State_" + id;  
  34.                         $(Student_Name).hide();  
  35.                         $(spanStudent_Name).show();  
  36.                         $(Student_Branch).hide();  
  37.                         $(spanStudent_Branch).show();  
  38.                         $(Student_City).hide();  
  39.                         $(spanStudent_City).show();  
  40.                         $(Student_State).hide();  
  41.                         $(spanStudent_State).show();  
  42.                         $(spanStudent_Name).text($(Student_Name).val());  
  43.                         $(spanStudent_Branch).text($(Student_Branch).val());  
  44.                         $(spanStudent_City).text($(Student_City).val());  
  45.                         $(spanStudent_State).text($(Student_State).val());  
  46.                     }  
  47.                     else {  
  48.                         alert('There is some error');  
  49.                     }  
  50.                 }  
  51.             });  
  52.         }  
  53.     }); 

Here also, first variables are declared for each Span and TextBox, then the Ajax call is executed.

In this Ajax call UpdateRecord of ShowData is called and some variables are passed through the data that will be utilized in the Controller class.

On successful completion of data, the Edit button will become visible again and Cancel, Edit will be hidden.

crud in webgrid

Step 8

Now we will work on the final Ajax call that will be for deleting the data.

  1. $(".delete").live("click"function () {  
  2.     var str = $(this).attr("id").split("_");  
  3.     id = str[1];  
  4.     var flag = confirm('Are you sure to delete ??');  
  5.     if (id != "" && flag) {  
  6.         $.ajax({  
  7.             type: "GET",  
  8.             contentType: "application/json; charset=utf-8",  
  9.             url: '@Url.Action("DeleteRecord", "ShowData")',  
  10.             data: { "id": id },  
  11.             dataType: "json",  
  12.             beforeSend: function () { },  
  13.             success: function (data) {  
  14.                 if (data.result == true) {  
  15.                     $("#Update_" + id).parents("tr").remove();  
  16.                 }  
  17.                 else {  
  18.                     alert('There is some error');  
  19.                 }  
  20.             }  
  21.         });  
  22.     }  
  23. });  
  24. /script> 

In this function I had passed the URL of DeleteRecord that is available in the ShowData Controller class, this will simply work on the Id of the Student and will pass the Id to the Controller whose work was explained in the last article.

crud in webgrid

Now your application is ready to be executed.


Similar Articles