Interacting with Data in JQuery Datatable in ASP.Net MVC

n

n

ninteracting-with-data-in-jquery-datatable-in-asp-net-mvc-jquery

n
n

nnn
nnn
nIn this article, I will walk you through how to build a sample web application with jquery datatable in ASP.Net MVC
n
n

nArticle Objective

nThis article aim is to show developers how to use interact with data loaded into jquery datatable via edit button, checkboxes and table row clicks.
n
n

nPrerequisites

nTo follow along with this article, you should have prior knowledge of ASP.Net, HTML, Jquery, and CSS. You should also have the following installed on your machine:
n
n

    n

  • ASP.Net
  • n

  • MS SQL Server
  • n

n
nnnnI also recommend that you read my previous article on jquery datatable server-side pagination.
n
n

nTable of Content

n

    n

  • Creating the Database and Tables
  • n

  • Creating ASP.Net Project
  • n

  • Loading Data to Jquery Datatable
  • n

  • Adding Action Button to Datatable
  • n

  • Access Data via Button Clicked
  • n

  • Adding Checkboxes
  • n

  • Access Data via checkboxes
  • n

n
nnnnn

nCreating the Database

nIn this tutorial, we will create three tables. The sample tables and data was taken from w3resource. Feel free to copy and run the script to follow along.
n
nSee below the table structure.
n
n

njquery-datatable-data-manipulation-table-structure

n
n

nCreating ASP.Net Project

nIn this section, let’s create and include all that we need to use jquery datatable in the project.
n
nCreate a new ASP.Net MVC application, and then include the datatable stylesheet and javascript library like so:
n
n

nCSSn

n

nnn

n
n

nJavascript Referencenn

n

nnnnn

n

nLoading Data to Jquery Datatablen

nI will not be talking much about loading data into datatable in this article. For details about this check out this article.
nnn
nnnnnnnnAdd a new folder to the root of the website named Services, and create a class inside it named DatatableService and modify the code to look like so:
n
nnn
nnNext, create an HttpPost actionresult in the home controller that will be responsible for sending data to our datatable. The actionresult method should look like so:nn
n

 nn [HttpPost]n        public JsonResult loadCustomers()n        {n            var draw = Request.Form.GetValues("draw").FirstOrDefault();n            var start = Request.Form.GetValues("start").FirstOrDefault();n            var length = Request.Form.GetValues("length").FirstOrDefault();nn            int pageSize = length != null ? Convert.ToInt32(length) : 0;n            int skip = start != null ? Convert.ToInt32(start) : 0;n            int recordsTotal = 0;nn            var model = _srv.GetCustomers();nn            recordsTotal = model.Count();nnn            var data = model.OrderBy(x => x.CUST_CODE).Skip(skip).Take(pageSize);nn            return Json(newn            {n                draw = draw,n                recordsFiltered = recordsTotal,n                recordsTotal = recordsTotal,n                data = datan            }, JsonRequestBehavior.AllowGet);n        }nn

nNow we need to create ajax method that will call our loadcustmer method so as to wire up the JQuery datatable. The whole javascript method look like so:nn
n

var table = $("#customerTable").DataTable({n            "processing": true, // for show progress barn            "serverSide": true, // for process server siden            "filter": true, // this is for disable filter (search box)n            "orderMulti": false, // for disable multiple column at oncen            //"dom": '<"top"i>rt<"bottom"lp><"clear">',n            "ajax": {n                "url": '@Url.Action("loadCustomers", "home")',n                "type": "POST",n                "datatype": "json"n            },n            "columns": [n                { "data": "CUST_CODE", "name": "CUST_CODE", "autoWidth": true },n                { "data": "CUST_NAME", "name": "CUST_NAME", "autoWidth": true },n                { "data": "CUST_CITY", "name": "CUST_CITY", "autoWidth": true },n                { "data": "CUST_COUNTRY", "name": "CUST_COUNTRY", "autoWidth": true },n                { "data": "PAYMENT_AMT", "name": "PAYMENT_AMT", "autoWidth": true }              nn            ]              nn        });nn

nIf everything is done correctly, build and run the application. The application should like this in the browser:n
n
n

njquery-datatable-data-manipulation-table-preview

n
n

nAdding Action Button to Datatablenn

nIn order to be able to perform actions like view, delete etc on the datatable we need to add buttons that will be clickable to perform those. To do this, we need to modify our javascript code by adding this line like so:
n
n

{ "data": null, "name": "Action", "defaultContent": ' | ', "autoWidth": true }n

n
nAnd also add an additional column to the table header. With this modification, the application should look like this:
n
n

njquery-datatable-data-manipulation-table-preview-with-button

n
n
n

nAccess Data via Button Clicked

n

n

n

nnn
nnWe have access to the data in JQuery Datatable row by calling the table.row.data() function like so:

n

   $(document).on("click", '.editLink', function (e) {nn      var data = table.row($(this).parents('tr')).data();n            console.log(data);nn  });nn  $(document).on("click", '.deleteLink', function (e) {nn   var data = table.row($(this).parents('tr')).data();n    console.log(data);nn   });nn

nAdding Checkboxes
nAdding checkbox to JQuery Datatable can be a little tricky. To add checkboxes we need to add additional column to the column and then override the render function like so:
n

  {n        "data": null,n         render: function (data, type, row) {n                  if (type === 'display') {n                       return '';n                   }n                   return data;n                },n   }n

n
nThe application should like this:n
n
n

njquery-datatable-with-checkboxes

n

n

n

n

n
n
n

nAccess Data via checkboxes

n

nLet’s say we have a button that when we click we want to get the row that of a checkbox that was checked, we can do that by using this method:

n

n

n

n

n

 nn      var custCodeArr = [];nn        $("#getCheckData").click(function (e) {n            e.preventDefault();n            custCodeArr.length = 0;n            custCodeArr = [];n            var rows = $(table.$('input[type="checkbox"]').map(function () {n                return $(this).prop("checked") ? $(this).val() : 0;n            }));nn            $.each(rows, function (i, v) {n                if (v != 0) {n                    custCodeArr.push(v);n                    }nn            });nn            console.log(custCodeArr);n        })nn

nIn this article, I have been able to show how to really interact with data within jquery datatable. Feel free to let me know what you think by dropping your comment and also clone the source from my github page.nnHappy Coding!.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top