MVC and JSON Action Results For Meaningful Feedback

I recently wrote an asynchronous pipeline for my MVC view that I thought could be beneficial for some of you. Let me set the scene.

The MVC view is a Kendo grid. However, it doesn't use the Kendo JSON data source because I am using the open source Kendo UI Core grid (you can find more information here). The Kendo UI Core components are simply JavaScript files that you put in your project and call when required. In this example, I am not using the API to load contents. I am simply creating a table and letting MVC Razor render it. Then, in my JavaScript, I call the Kendo JavaScript methods to format and complete the grid render. The Kendo UI Core gives very useful functionality like pagination, sorting, filtering, column ordering and so on. So this is what my table looks like. You can see that I am using Bootstrap too.

  1. <div class="col-md-12">  
  2. <table id="user-grid" class="table table-bordered table-striped">  
  3. <thead>  
  4. <tr>  
  5.     <th>@Html.DisplayNameFor(model => model.Id)</th>  
  6.     <th>@Html.DisplayNameFor(model => model.UserName)</th>  
  7.     <th>@Html.DisplayNameFor(model => model.FirstName)</th>  
  8.     <th>@Html.DisplayNameFor(model => model.LastName)</th>  
  9.     <th>@Html.DisplayNameFor(model => model.Email)</th>  
  10.     <th>@Html.DisplayNameFor(model => model.IsVisible)</th>  
  11.     <th></th>  
  12. </tr>  
  13. </thead>  
  14. <tbody>  
  15. @foreach (var item in Model) {  
  16. <tr>  
  17.     <td>@Html.DisplayFor(modelItem => item.Id)</td>  
  18.     <td>@Html.DisplayFor(modelItem => item.UserName)</td>  
  19.     <td>@Html.DisplayFor(modelItem => item.FirstName)</td>  
  20.     <td>@Html.DisplayFor(modelItem => item.LastName)</td>  
  21.     <td>@Html.DisplayFor(modelItem => item.Email)</td>  
  22.     <td>@Html.DisplayFor(modelItem => item.IsVisible)</td>  
  23.     <td></td>  
  24. </tr>  
  25. }  
  26. </tbody>  
  27. </table>  
  28. </div>  
So now have a nicely formatted table. But we can't do anything with the records in the table. Kendo gives us this functionality. You can see in the code above that there is a blank table header column and also a blank table cell for each row. We can configure Kendo to render command buttons in each row of our table. And it's all done via JavaScript in the view.

We will use the table ID as the selector for the Kendo JavaScript. Read the documentation (link above) to understand the configuration settings.
  1. $(function() {  
  2.     $("#user-grid").kendoGrid({  
  3.         height: 500,  
  4.         sortable: true,  
  5.         resizable: true,  
  6.         reorderable: true,  
  7.         columnMenu: true,  
  8.         columns: [  
  9.             { field: "Id", title: "Id", width: 50 },  
  10.             { field: "UserName", title: "UserName", width: 120 },  
  11.             { field: "FirstName", title: "FirstName" },  
  12.             { field: "LastName", title: "LastName" },  
  13.             { field: "Email", title: "Email" },  
  14.             { field: "IsVisible", title: "IsVisible", width: 100 },  
  15.             {  
  16.                 command: [  
  17.                     { text: "Edit", click: editItem },  
  18.                     { text: "Delete", click: deleteItem }  
  19.                 ],  
  20.                 title: " ",  
  21.                 width: 200  
  22.             }  
  23.         ]  
  24.     });  
  25. });  
The columns property has a command property that lets you configure command buttons for any of the columns you want. You can see that I have created two command buttons. One is an Edit button and the other is a Delete button. Each of these commands have a click method associated with it that can point to any JavaScript function you like. Here is the Edit JavaScript function that I used for these two command buttons.
  1. function editItem(e) {  
  2.     // stop the button doing it's default behaviour  
  3.     e.preventDefault();  
  4.     // get the button's parent row so we can get data from the columns    
  5.     var dataItem = this.dataItem($(e.currentTarget).closest("tr"));  
  6.     // build the URL for the MVC action that will do something useful with the data  
  7.     var baseUrl = '@Url.Action("Edit", "Users")';  
  8.     // a function that navigates to the action (I re-use this in the next command button function too)  
  9.     go(baseUrl + "/" + dataItem.Id);  
  10. }  
  11. function go(url) {  
  12.     window.location = url;  
  13. }  
So now we have a table with functional rows and an edit command button that will take the user to the edit view for modification. But the delete command is different. We don't need to go to a view (UI) in order to delete the record. We really just want to click the button, have MVC delete the record, refresh the grid and provide a message to say whether it worked or not. This is where the asynchronous MVC calls come in. We could just send the user to a view when the delete button is clicked and then return to the grid once it's finished but that repaints the UI. So we will use an action result called JSON Result to asynchronously do the delete and return a result message to the user. First, let me show you the delete JavaScript function. I am using a component called BootstrapDialog to show a nice dialog prompt. This simply says “Are you sure?”.
  1. function deleteItem(e) {  
  2.     var dataItem = this.dataItem($(e.currentTarget).closest("tr"));  
  3.     BootstrapDialog.show({  
  4.         title: 'Delete This Item',  
  5.         message: 'This will permanently delete this user and they will not be able to log in. Are you sure?',  
  6.         buttons: [  
  7.         {  
  8.             label: 'Yes',  
  9.             action: function(dialog) {  
  10.                 $.ajax({  
  11.                     url: '@Url.Action("Delete", "Users")',  
  12.                         type: 'POST',  
  13.                         data: { 'id': dataItem.Id },  
  14.                         success: function (result) {  
  15.                             var r = JSON.parse(result);  
  16.                             toastr.success(r.Message);  
  17.                             $("#user-grid").refresh();  // not yet implemented  
  18.                             dialog.close();  
  19.                         },  
  20.                         error: function(result) {  
  21.                             toastr.error(result.Message);  
  22.                             dialog.close();  
  23.                         }  
  24.                     });  
  25.                 }  
  26.             }, {  
  27.                 label: 'No',  
  28.                 action: function(dialog) {  
  29.                     // not yet implemented  
  30.                 }  
  31.             }  
  32.         ]  
  33.     });  
  34. }  
Let me explain in dot points what will happen when the user clicks the delete button. 
  1. A dialog appears asking the user to confirm they want to delete the record. The user clicks Yes.

  2. JavaScript does an HTTP Post action to the MVC action Users/Delete.

  3. The MVC action returns a JSON result message.

  4. AJAX determines if the POST was successful or not.

  5. The JSON result is parsed and displayed in a Toastr notification message.

  6. JavaScript refreshes the Kendo grid.

To make this all work, the MVC action must return a JSON object so that the JavaScript function can consume it. Here is the MVC Delete action code.

  1. [HttpPost]  
  2. public JsonResult Delete(int id)  
  3. {  
  4.     string errMessage;  
  5.     bool delete = _builder.DeleteUser(id, out errMessage);  
  6.     ViewModelJson result = new ViewModelJson()  
  7.     {  
  8.         Result = delete,  
  9.         Message = errMessage  
  10.     };  
  11.     var serializer = new JavaScriptSerializer();  
  12.     var serializedResult = serializer.Serialize(result);  
  13.     return Json(serializedResult);  
  14. }  
  15. ///   
  16. /// A custom class with properties that carry useful data back to the client.   
  17. /// You can extend this class as much as you like to transport more data if you want  
  18. ///   
  19. public class ViewModelJson  
  20. {  
  21.     public bool Result { get; set; }  
  22.     public string Message { get; set; }  
  23. }  
So, as a result, the MVC action returns serialized JSON to the view. The view parses the JSON and decides how to render it to the user.

Feel free to make comments on this and I hope you found it useful.

Until next time...


Similar Articles