Header Ads

ASP.NET MVC5: Buttons in Datatables Jquery plugin

Table view is one of the most important and basic form of presenting data on the web page. However, adding action to each row is equally important simply because action for each row leads to different result. Jquery Datatables plugin is one of the most used plugin as I have demonstrate its integration in ASP.NET MVC5 - Datables Plugin Server Side Integration in one of my article.
In today's tutorial I will demonstrate the idea of using any kind of action within jquery base datatables plugin.


Prerequisites:

Following are some prerequisites before you proceed any further in this tutorial:
  1. Knowledge about Datatebles plugin.
  2. Knowledge about ASP.NET MVC5.  
  3. Knowledge about HTML.  
  4. Knowledge about Javascript.
  5. Knowledge about AJAX.
  6. Knowledge about CSS.
  7. Knowledge about Bootstrap.
  8. Knowledge about C# programming.  
  9. Knowledge about C# LINQ.  
  10. Knowledge about JQuery.  
  11. Knowledge about WebMethod attribute
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.

Download Now!

Let's begin now.

1) Create new MVC5 web application project and name it "MVC5DatatablesWithButton".
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")

    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css" />

    <!-- Data table -->
    <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 &copy; @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")

    <!-- Data Table -->
    <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 create a basic layout for the web page and in clude references to the require libraries and JQuery Datatables plugin.

3) Now, create "Models\SalesOrderDetail.cs" file by and replace below code in this file i.e.

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.

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

        /// <summary>
        /// GET: Plugin method.
        /// </summary>
        /// <returns>Returns - index view page</returns> 
        public ActionResult Index(string Id)
        {
            // Verification
            if (string.IsNullOrEmpty(Id))
            {
                // Info.
                return this.View();
            }

            // Initialization.
            this.ViewBag.alert = Id;

            // Info.
            return this.View();
        }

        #endregion

        #region Get data method.

        /// <summary>
        /// GET: /Plugin/GetData
        /// </summary>
        /// <returns>Return data</returns>
        public ActionResult GetData()
        {
            // Initialization.
            JsonResult result = new JsonResult();

            try
            {
                // Initialization.
                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]);

                // Loading.
                List<SalesOrderDetail> data = this.LoadData();

                // Total record count.
                int totalRecords = data.Count;

                // Verification.
                if (!string.IsNullOrEmpty(search) &&
                    !string.IsNullOrWhiteSpace(search))
                {
                    // Apply 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();
                }

                // Sorting.
                data = this.SortByColumnWithOrder(order, orderDir, data);

                // Filter record count.
                int recFilter = data.Count;

                // Apply pagination.
                data = data.Skip(startRec).Take(pageSize).ToList();

                // Loading drop down lists.
                result = this.Json(new { draw = Convert.ToInt32(draw), recordsTotal = totalRecords, recordsFiltered = recFilter, data = data }, JsonRequestBehavior.AllowGet);
            }
            catch (Exception ex)
            {
                // Info
                Console.Write(ex);
            }

            // Return info.
            return result;
        }

        #endregion

        #region Helpers

        #region Load Data

        /// <summary>
        /// Load data method.
        /// </summary>
        /// <returns>Returns - Data</returns>
        private List<SalesOrderDetail> LoadData()
        {
            // Initialization.
            List<SalesOrderDetail> lst = new List<SalesOrderDetail>();

            try
            {
                // Initialization.
                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));

                // Read file.
                while ((line = sr.ReadLine()) != null)
                {
                    // Initialization.
                    SalesOrderDetail infoObj = new SalesOrderDetail();
                    string[] info = line.Split(',');

                    // Setting.
                    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>";

                    // Adding.
                    lst.Add(infoObj);
                }

                // Closing.
                sr.Dispose();
                sr.Close();
            }
            catch (Exception ex)
            {
                // info.
                Console.Write(ex);
            }

            // info.
            return lst;
        }

        #endregion

        #region Sort by column with order method

        /// <summary>
        /// Sort by column with order method.
        /// </summary>
        /// <param name="order">Order parameter</param>
        /// <param name="orderDir">Order direction parameter</param>
        /// <param name="data">Data parameter</param>
        /// <returns>Returns - Data</returns>
        private List<SalesOrderDetail> SortByColumnWithOrder(string order, string orderDir, List<SalesOrderDetail> data)
        {
            // Initialization.
            List<SalesOrderDetail> lst = new List<SalesOrderDetail>();

            try
            {
                // Sorting
                switch (order)
                {
                    case "0":
                        // Setting.
                        lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.Sr).ToList()
                                                                                                 : data.OrderBy(p => p.Sr).ToList();
                        break;

                    case "1":
                        // Setting.
                        lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.OrderTrackNumber).ToList()
                                                                                                 : data.OrderBy(p => p.OrderTrackNumber).ToList();
                        break;

                    case "2":
                        // Setting.
                        lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.Quantity).ToList()
                                                                                                 : data.OrderBy(p => p.Quantity).ToList();
                        break;

                    case "3":
                        // Setting.
                        lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.ProductName).ToList()
                                                                                                 : data.OrderBy(p => p.ProductName).ToList();
                        break;

                    case "4":
                        // Setting.
                        lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.SpecialOffer).ToList()
                                                                                                   : data.OrderBy(p => p.SpecialOffer).ToList();
                        break;

                    case "5":
                        // Setting.
                        lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.UnitPrice).ToList()
                                                                                                 : data.OrderBy(p => p.UnitPrice).ToList();
                        break;

                    case "6":
                        // Setting.
                        lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.UnitPriceDiscount).ToList()
                                                                                                 : data.OrderBy(p => p.UnitPriceDiscount).ToList();
                        break;

                    default:

                        // Setting.
                        lst = orderDir.Equals("DESC", StringComparison.CurrentCultureIgnoreCase) ? data.OrderByDescending(p => p.Sr).ToList()
                                                                                                 : data.OrderBy(p => p.Sr).ToList();
                        break;
                }
            }
            catch (Exception ex)
            {
                // info.
                Console.Write(ex);
            }

            // info.
            return lst;
        }

        #endregion

        #endregion
    }
}

The above piece of code consist of Index(...), LoadData(), GetData() & SortByColumnWithOrder(...) methods in which Index(...) method will return the details for our view page, LoadData() method will simply loads data from text file into list and also I have created HTML link as string and map that value to our new action property for user to perform action on each row. Then, we have created SortByColumnWithOrder(...) method which will perform sorting and ordering of our table grind on the web page and handles 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 create an HTML link as string and map 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.

            // Initialization.
            this.ViewBag.alert = Id;

5) Create "Views\Home\_ViewListPartial.cshtml" & "Views\Home\Index.cshtml" files and replace following code in it i.e.

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 create 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.

<th></th>

6) Now, create "Scripts\custom-datatable.js"file and replace following code in it i.e.

$(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 add the button action as a column and make it non searchable and non-sortable by the jquery datatables plugin.

7) Let, execute the project now and you will be able to see following i.e.


When you click any button in jquery datatables plugin, you will see below result i.e.


Conclusion

In this article, you will learn about adding any sort of button, link or action within jquery datatables which is in correspondent to a particular row in order to perform operations like CRUD (Create, Read, Update, Delete). You will also learn to use Viewbag property in HTML code and on server side as well.

2 comments: