jQuery DataTables server-side processing using ASP.NET WebForms

rebelliard picture rebelliard · Aug 20, 2010 · Viewed 36.3k times · Source

Problem:

  • jQuery DataTables server-side processing using ASP.NET WebForms.

Solution:

  • Darin Dimitrov answered the question using an example which pages and sorts, but doesn't do any searching. Here's my **basic** modification of his work to make searching work on his example:
public class Data : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Paging parameters:
        var iDisplayLength = int.Parse(context.Request["iDisplayLength"]);
        var iDisplayStart = int.Parse(context.Request["iDisplayStart"]);

        // Sorting parameters
        var iSortCol = int.Parse(context.Request["iSortCol_0"]);
        var iSortDir = context.Request["sSortDir_0"];

        // Search parameters
        var sSearch = context.Request["sSearch"];

        // Fetch the data from a repository (in my case in-memory)
        var persons = Person.GetPersons();

        // Define an order function based on the iSortCol parameter
        Func<Person, object> order = person => iSortCol == 0 ? (object) person.Id : person.Name;

        // Define the order direction based on the iSortDir parameter
        persons = "desc" == iSortDir ? persons.OrderByDescending(order) : persons.OrderBy(order);

        // prepare an anonymous object for JSON serialization
        var result = new
                         {
                             iTotalRecords = persons.Count(),
                             iTotalDisplayRecords = persons.Count(),
                             aaData = persons
                                 .Where(p => p.Name.Contains(sSearch))  // Search: Avoid Contains() in production
                                 .Where(p => p.Id.ToString().Contains(sSearch))
                                 .Select(p => new[] {p.Id.ToString(), p.Name})
                                 .Skip(iDisplayStart)   // Paging
                                 .Take(iDisplayLength)
                         };

        var serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(result);
        context.Response.ContentType = "application/json";
        context.Response.Write(json);
    }

    public bool IsReusable { get { return false; } }
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public static IEnumerable<Person> GetPersons()
    {
        for (int i = 0; i < 57; i++)
        {
            yield return new Person { Id = i, Name = "name " + i };
        }
    }
}

Answer

Darin Dimitrov picture Darin Dimitrov · Aug 30, 2010

I wrote a simple example that should illustrate the idea.

Start by writing a generic handler for handling data on the server side (Data.ashx but this could be a web page, web service, anything server side script capable of returning JSON formated data):

public class Data : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        // Those parameters are sent by the plugin
        var iDisplayLength = int.Parse(context.Request["iDisplayLength"]);
        var iDisplayStart = int.Parse(context.Request["iDisplayStart"]);
        var iSortCol = int.Parse(context.Request["iSortCol_0"]);
        var iSortDir = context.Request["sSortDir_0"];

        // Fetch the data from a repository (in my case in-memory)
        var persons = Person.GetPersons();

        // Define an order function based on the iSortCol parameter
        Func<Person, object> order = p => 
        {
            if (iSortCol == 0) 
            { 
                return p.Id; 
            }
            return p.Name;
        };

        // Define the order direction based on the iSortDir parameter
        if ("desc" == iSortDir)
        {
            persons = persons.OrderByDescending(order);
        }
        else
        {
            persons = persons.OrderBy(order);
        }

        // prepare an anonymous object for JSON serialization
        var result = new
        {
            iTotalRecords = persons.Count(),
            iTotalDisplayRecords = persons.Count(),
            aaData = persons
                .Select(p => new[] { p.Id.ToString(), p.Name })
                .Skip(iDisplayStart)
                .Take(iDisplayLength)
        };

        var serializer = new JavaScriptSerializer();
        var json = serializer.Serialize(result);
        context.Response.ContentType = "application/json";
        context.Response.Write(json);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }

    public static IEnumerable<Person> GetPersons()
    {
        for (int i = 0; i < 57; i++)
        {
            yield return new Person
            {
                Id = i,
                Name = "name " + i
            };
        }
    }
}

And then a WebForm:

<%@ Page Title="Home Page" Language="C#" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head id="Head1" runat="server">
    <title></title>
    <link rel="stylesheet" type="text/css" href="/styles/demo_table.css" /> 
    <script type="text/javascript" src="/scripts/jquery-1.4.1.js"></script>
    <script type="text/javascript" src="/scripts/jquery.dataTables.js"></script>
    <script type="text/javascript">
        $(function () {
            $('#example').dataTable({
                'bProcessing': true,
                'bServerSide': true,
                'sAjaxSource': '/data.ashx'
            });
        });
    </script>
</head>
<body>
    <form id="Form1" runat="server">
        <table cellpadding="0" cellspacing="0" border="0" class="display" id="example"> 
            <thead> 
            <tr> 
                <th>ID</th> 
                <th>Name</th> 
            </tr> 
            </thead> 
            <tbody> 
            <tr> 
                <td colspan="5" class="dataTables_empty">Loading data from server</td> 
            </tr> 
            </tbody> 
        </table>
    </form>
</body>
</html>

The example is oversimplified but I hope it will illustrate the basics on how to get stared.