Table view is one of the most important and basic forms of presenting data on a web page. However, adding action to each row is equally important simply because action for each row leads to different results. Jquery Datatables plugin is one of the most used plugins, as I have demonstrated its integration in one of my articles, ASP.NET MVC5 - Datables Plugin Server Side Integration.
In this article I will demonstrate the idea of using any kind of action within jquery based datatables plugin.
Following are some prerequisites before you proceed any further in this tutorial,
- Knowledge about ASP.NET MVC5.
- Knowledge about HTML.
- Knowledge about Javascript.
- Knowledge about AJAX.
- Knowledge about CSS.
- Knowledge about Bootstrap.
- Knowledge about C# programming.
- Knowledge about C# LINQ.
- Knowledge about JQuery.
- Knowledge about WebMethod attribute
- Knowledge about Datatebles plugin
You can download the complete source code for this tutorial or you can follow the step by step discussion below. The sample code is developed in Microsoft Visual Studio 2015 Enterprise. I am using SalesOrderDetail table extract from Adventure Works Sample Database.
Let's begin now.
Step 1
Create new MVC5 web application project and name it "MVC5DatatablesWithButton".
Step 2
Open "Views\Shared\_Layout.cshtml" page and replace following code in it i.e.
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0">
- <title>@ViewBag.Title</title>
- @Styles.Render("~/Content/css")
- @Scripts.Render("~/bundles/modernizr")
-
-
- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />
-
-
- <link rel="stylesheet" href="https://cdn.datatables.net/1.10.10/css/dataTables.bootstrap.min.css " />
-
- @* Custom *@
- @Styles.Render("~/Content/css/custom-style")
- </head>
- <body>
- <div class="navbar navbar-inverse navbar-fixed-top">
- <div class="container">
- <div class="navbar-header">
- <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- <span class="icon-bar"></span>
- </button>
- </div>
- </div>
- </div>
- <div class="container body-content">
- @RenderBody()
- <hr />
- <footer>
- <center>
- <p><strong>Copyright © @DateTime.Now.Year - <a href="http://www.asmak9.com/">Asma's Blog</a>.</strong> All rights reserved.</p>
- </center>
- </footer>
- </div>
-
- @Scripts.Render("~/bundles/jquery")
- @Scripts.Render("~/bundles/bootstrap")
-
-
- <script src="https://cdn.datatables.net/1.10.10/js/jquery.dataTables.min.js" type="text/javascript"></script>
- <script src="https://cdn.datatables.net/1.10.10/js/dataTables.bootstrap.min.js" type="text/javascript"></script>
- @Scripts.Render("~/bundles/custom-datatable")
-
- @RenderSection("scripts", required: false)
- </body>
- </html>
In the above code, I have simply created a basic layout for the web page and included references to the required libraries and JQuery Datatables plugin.
Step 3
Now, create "Models\SalesOrderDetail.cs" file by and replace below code in this file
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Web;
-
- namespace MVC5DatatablesWithButton.Models
- {
- public class SalesOrderDetail
- {
- public int Sr { get; set; }
- public string OrderTrackNumber { get; set; }
- public int Quantity { get; set; }
- public string ProductName { get; set; }
- public string SpecialOffer { get; set; }
- public double UnitPrice { get; set; }
- public double UnitPriceDiscount { get; set; }
- public string Action { get; set; }
- }
- }
In the above code, we have simply created our model to map data from text file to main memory with the addition a new property i.e. Action of type string. This property will be used to place the content of our action on Datatables UI grid for each row.
Step 4
Now, create "Controllers\HomeController.cs" file and replace following code in it i.e.
- using MVC5DatatablesWithButton.Models;
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Reflection;
- using System.Web;
- using System.Web.Mvc;
-
- namespace MVC5DatatablesWithButton.Controllers
- {
- public class HomeController : Controller
- {
- #region Index method
-
-
-
-
-
- public ActionResult Index(string Id)
- {
-
- if (string.IsNullOrEmpty(Id))
- {
-
- return this.View();
- }
-
-
- this.ViewBag.alert = Id;
-
-
- return this.View();
- }
-
- #endregion
-
- #region Get data method.
-
-
-
-
-
- public ActionResult GetData()
- {
-
- JsonResult result = new JsonResult();
-
- try
- {
-
- string search = Request.Form.GetValues("search[value]")[0];
- string draw = Request.Form.GetValues("draw")[0];
- string order = Request.Form.GetValues("order[0][column]")[0];
- string orderDir = Request.Form.GetValues("order[0][dir]")[0];
- int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
- int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
-
-
- List<SalesOrderDetail> data = this.LoadData();
-
-
- int totalRecords = data.Count;
-
-
- if (!string.IsNullOrEmpty(search) &&
- !string.IsNullOrWhiteSpace(search))
- {
-
- data = data.Where(p => p.Sr.ToString().ToLower().Contains(search.ToLower()) ||
- p.OrderTrackNumber.ToLower().Contains(search.ToLower()) ||
- p.Quantity.ToString().ToLower().Contains(search.ToLower()) ||
- p.ProductName.ToLower().Contains(search.ToLower()) ||
- p.SpecialOffer.ToLower().Contains(search.ToLower()) ||
- p.UnitPrice.ToString().ToLower().Contains(search.ToLower()) ||
- p.UnitPriceDiscount.ToString().ToLower().Contains(search.ToLower())).ToList();
- }
-
-
- data = this.SortByColumnWithOrder(order, orderDir, data);
-
-
- int recFilter = data.Count;
-
-
- data = data.Skip(startRec).Take(pageSize).ToList();
-
-
- result = this.Json(new { draw = Convert.ToInt32(draw), recordsTotal = totalRecords, recordsFiltered = recFilter, data = data }, JsonRequestBehavior.AllowGet);
- }
- catch (Exception ex)
- {
-
- Console.Write(ex);
- }
-
-
- return result;
- }
-
- #endregion
-
- #region Helpers
-
- #region Load Data
-
-
-
-
-
- private List<SalesOrderDetail> LoadData()
- {
-
- List<SalesOrderDetail> lst = new List<SalesOrderDetail>();
-
- try
- {
-
- string line = string.Empty;
- string srcFilePath = "content/files/SalesOrderDetail.txt";
- var rootPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase);
- var fullPath = Path.Combine(rootPath, srcFilePath);
- string filePath = new Uri(fullPath).LocalPath;
- StreamReader sr = new StreamReader(new FileStream(filePath, FileMode.Open, FileAccess.Read));
-
-
- while ((line = sr.ReadLine()) != null)
- {
-
- SalesOrderDetail infoObj = new SalesOrderDetail();
- string[] info = line.Split(',');
-
-
- infoObj.Sr = Convert.ToInt32(info[0].ToString());
- infoObj.OrderTrackNumber = info[1].ToString();
- infoObj.Quantity = Convert.ToInt32(info[2].ToString());
- infoObj.ProductName = info[3].ToString();
- infoObj.SpecialOffer = info[4].ToString();
- infoObj.UnitPrice = Convert.ToDouble(info[5].ToString());
- infoObj.UnitPriceDiscount = Convert.ToDouble(info[6].ToString());
-
- infoObj.Action = "<a class='btn btn-warning' href='" + this.Url.Action("Index", "Home", new { Id = infoObj.Sr }) + "'>Click Me</a>";
-
-
- lst.Add(infoObj);
- }
-
-
- sr.Dispose();
- sr.Close();
- }
- catch (Exception ex)
- {
-
- Console.Write(ex);
- }
-
-
- return lst;
- }
-
- #endregion
-
- #region Sort by column with order method
-
-
-
-
-
-
-
-
- private List<SalesOrderDetail> SortByColumnWithOrder(string order, string orderDir, List<SalesOrderDetail> data)
- {
-
- List<SalesOrderDetail> lst = new List<SalesOrderDetail>();
-
- try
- {
-
- switch (order)
- {
- case "0":
-
- lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.Sr).ToList()
- : data.OrderBy(p => p.Sr).ToList();
- break;
-
- case "1":
-
- lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.OrderTrackNumber).ToList()
- : data.OrderBy(p => p.OrderTrackNumber).ToList();
- break;
-
- case "2":
-
- lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.Quantity).ToList()
- : data.OrderBy(p => p.Quantity).ToList();
- break;
-
- case "3":
-
- lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.ProductName).ToList()
- : data.OrderBy(p => p.ProductName).ToList();
- break;
-
- case "4":
-
- lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.SpecialOffer).ToList()
- : data.OrderBy(p => p.SpecialOffer).ToList();
- break;
-
- case "5":
-
- lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.UnitPrice).ToList()
- : data.OrderBy(p => p.UnitPrice).ToList();
- break;
-
- case "6":
-
- lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.UnitPriceDiscount).ToList()
- : data.OrderBy(p => p.UnitPriceDiscount).ToList();
- break;
-
- default:
-
-
- lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.Sr).ToList()
- : data.OrderBy(p => p.Sr).ToList();
- break;
- }
- }
- catch (Exception ex)
- {
-
- Console.Write(ex);
- }
-
-
- return lst;
- }
-
- #endregion
-
- #endregion
- }
- }
The above piece of code consists of Index(...), LoadData(), GetData() & SortByColumnWithOrder(...) methods in which Index(...) method will return the details for our view page, LoadData() method will simply load data from text file into list and also I have created HTML link as string and mapped that value to our new action property for the user to perform an action on each row. Then, we have created SortByColumnWithOrder(...) method which will perform sorting and ordering of our table grid on the web page and handle it on server side. Finally, I have created an ajax call web method that will process and map information from server side to the datatables jquery plugin.
The important change is in LoadData(...) method i.e. in LoadData(...) method we have created an HTML link as string and mapped that value to our data grid actionable property i.e.
- infoObj.Action = "<a class='btn btn-warning' href='" + this.Url.Action("Index", "Home", new { Id = infoObj.Sr }) + "'>Click Me</a>";
And in Index(...) action method, we are simply returning clickable row ID as Viewbag property to see button clicks in action i.e.
Step 5
Create "Views\Home\_ViewListPartial.cshtml" & "Views\Home\Index.cshtml" files and replace following code in it i.e.
Views\Home\_ViewListPartial.cshtml
- Views\Home\_ViewListPartial.cshtml
- <section>
- <div class="well bs-component">
- <br />
-
- <div class="row">
- <div>
- <table class="table table-striped table-bordered table-hover"
- id="TableId"
- cellspacing="0"
- align="center"
- width="100%">
- <thead>
- <tr>
- <th>Sr</th>
- <th>Order Track Number</th>
- <th>Quantity</th>
- <th>Product Name</th>
- <th>Special Offer</th>
- <th>Unit Price</th>
- <th>Unit Price Discount</th>
-
- <th></th>
- </tr>
- </thead>
- </table>
- </div>
- </div>
- </div>
- </section>
View\Home\Index.cshtml
- @{
- ViewBag.Title = "ASP.NET MVC5 - Jquery Datatables with Button";
- }
-
- <div class="row">
- @Html.Hidden("Idval", (string)ViewBag.alert)
- </div>
-
- <div class="row">
- <div class="panel-heading">
- <div class="col-md-8 custom-heading3">
- <h3>
- <i class="fa fa-table"></i>
- <span>ASP.NET MVC5 - Jquery Datatables with Button</span>
- </h3>
- </div>
- </div>
- </div>
-
- <div class="row">
- <section class="col-md-12 col-md-push-0">
- @Html.Partial("_ViewListPartial")
- </section>
- </div>
-
- <script type="text/javascript">
- var idVal = document.getElementById("Idval").value;
-
- if (idVal != null && idVal != "")
- {
- alert(idVal);
- }
- </script>
In the above code, I have simply created the view code for the page which will display the grid view by using JQuery DataTables plugin. I have divided the page into two parts for better manageability.
Here, the important change in the "Views\Home\_ViewListPartial.cshtml" file is the new header column which will contain our action button within the datatables jquery plugin i.e.
Step 6
Now, create "Scripts\custom-datatable.js"file and replace the following code in it:
- $(document).ready(function () {
- $('#TableId').DataTable(
- {
- "columnDefs": [
- { "width": "5%", "targets": [0] },
- { "width": "10%", "searchable": false, "orderable": false, "targets": [7] },
- { "className": "text-center custom-middle-align", "targets": [0, 1, 2, 3, 4, 5, 6, 7] },
- ],
- "language":
- {
- "processing": "<div class='overlay custom-loader-background'><i class='fa fa-cog fa-spin custom-loader-color'></i></div>"
- },
- "processing": true,
- "serverSide": true,
- "ajax":
- {
- "url": "/Home/GetData",
- "type": "POST",
- "dataType": "JSON"
- },
- "columns": [
- { "data": "Sr" },
- { "data": "OrderTrackNumber" },
- { "data": "Quantity" },
- { "data": "ProductName" },
- { "data": "SpecialOffer" },
- { "data": "UnitPrice" },
- { "data": "UnitPriceDiscount" },
- { "data": "Action" }
- ]
- });
- });
In the above code, we have simply configured basic settings for our jquery datatables plugin and also added the button action as a column and made it non searchable and non-sortable by the jquery datatables plugin.
Step 7
Let's execute the project now and you will be able to see the following:
When you click any button in jquery datatables plugin, you will see the below result:
Conclusion
In this article, you learned about adding any sort of button, link or action within jquery datatables which corresponds to a particular row in order to perform operations like CRUD (Create, Read, Update, Delete). You also learned to use Viewbag property in HTML code and on the server side as well.