Header Ads

Interacting with Data in JQuery Datatable in ASP.Net MVC

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



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

Article Objective

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

Prerequisites

To 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:

  • ASP.Net
  • MS SQL Server

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

Table of Content

  • Creating the Database and Tables
  • Creating ASP.Net Project
  • Loading Data to Jquery Datatable
  • Adding Action Button to Datatable
  • Access Data via Button Clicked
  • Adding Checkboxes
  • Access Data via checkboxes


Creating the Database

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

See below the table structure.

jquery-datatable-data-manipulation-table-structure

Creating ASP.Net Project

In this section, let's create and include all that we need to use jquery datatable in the project.

Create a new ASP.Net MVC application, and then include the datatable stylesheet and javascript library like so:

CSS





Javascript Reference






Loading Data to Jquery Datatable

I will not be talking much about loading data into datatable in this article. For details about this check out this article.

Add 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:

 

   public class DatatableService
    {
        DatatableEntities _db;
        public DatatableService()
        {
            _db = new DatatableEntities();
        }

        public IQueryable GetCustomers()
        {
            return _db.CUSTOMERs;
        }
    }


Next, 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:
 

 [HttpPost]
        public JsonResult loadCustomers()
        {
            var draw = Request.Form.GetValues("draw").FirstOrDefault();
            var start = Request.Form.GetValues("start").FirstOrDefault();
            var length = Request.Form.GetValues("length").FirstOrDefault();

            int pageSize = length != null ? Convert.ToInt32(length) : 0;
            int skip = start != null ? Convert.ToInt32(start) : 0;
            int recordsTotal = 0;

            var model = _srv.GetCustomers();

            recordsTotal = model.Count();


            var data = model.OrderBy(x => x.CUST_CODE).Skip(skip).Take(pageSize);

            return Json(new
            {
                draw = draw,
                recordsFiltered = recordsTotal,
                recordsTotal = recordsTotal,
                data = data
            }, JsonRequestBehavior.AllowGet);
        }

Now 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:
var table = $("#customerTable").DataTable({
            "processing": true, // for show progress bar
            "serverSide": true, // for process server side
            "filter": true, // this is for disable filter (search box)
            "orderMulti": false, // for disable multiple column at once
            //"dom": '<"top"i>rt<"bottom"lp><"clear">',
            "ajax": {
                "url": '@Url.Action("loadCustomers", "home")',
                "type": "POST",
                "datatype": "json"
            },
            "columns": [
                { "data": "CUST_CODE", "name": "CUST_CODE", "autoWidth": true },
                { "data": "CUST_NAME", "name": "CUST_NAME", "autoWidth": true },
                { "data": "CUST_CITY", "name": "CUST_CITY", "autoWidth": true },
                { "data": "CUST_COUNTRY", "name": "CUST_COUNTRY", "autoWidth": true },
                { "data": "PAYMENT_AMT", "name": "PAYMENT_AMT", "autoWidth": true }              

            ]              

        });

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

jquery-datatable-data-manipulation-table-preview

Adding Action Button to Datatable

In 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:

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

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

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


Access Data via Button Clicked


We have access to the data in JQuery Datatable row by calling the table.row.data() function like so:
   $(document).on("click", '.editLink', function (e) {

      var data = table.row($(this).parents('tr')).data();
            console.log(data);

  });

  $(document).on("click", '.deleteLink', function (e) {

   var data = table.row($(this).parents('tr')).data();
    console.log(data);

   });

Adding Checkboxes
Adding 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:
  {
        "data": null,
         render: function (data, type, row) {
                  if (type === 'display') {
                       return '';
                   }
                   return data;
                },
   }

The application should like this:

jquery-datatable-with-checkboxes


Access Data via checkboxes

Let'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:


 

      var custCodeArr = [];

        $("#getCheckData").click(function (e) {
            e.preventDefault();
            custCodeArr.length = 0;
            custCodeArr = [];
            var rows = $(table.$('input[type="checkbox"]').map(function () {
                return $(this).prop("checked") ? $(this).val() : 0;
            }));

            $.each(rows, function (i, v) {
                if (v != 0) {
                    custCodeArr.push(v);
                    }

            });

            console.log(custCodeArr);
        })

In 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. Happy Coding!.

No comments

Powered by Blogger.