This is an old revision of the document!


DataTables with WebForms

The Datatables jQuery plugin is a powerful plugin for showing data in a table format. Zack Owens gives a good example of doing DataTables Server Side processing with C# on his blog. However this is written for MVC pages and does not work with Webforms and Page methods. This tutorial shows how to adapt his code to work in this scenario.

I use a web form design layout, primarily because I haven't learnt MVC yet. Someday I will, but for now Webforms does what I want so I'm sticking with what I know. However I am looking to move the presentation into Javascript with jQuery, and the DataTables control provides a lot of functionality, especially when combined with Zack Owens generic backend parser, which magically handles sorting and filtering (paginating appears to be a bit off though!).

The main problem applying this to a Page Method (not sure about .asmx Web servies methods but it may be the same. Page methods are Web services combined into standard .aspx pages). See here for a tutorial on page methods.
A page methods expects to send a recieve data in a specific format (design to integrate with Microsoft's ScriptManager client side framework). MVC is more forgiving and works with the standard Datatables method, but we need to make some small conversions to make it work for us. Fortunately this is very easy, by overriding the “fnServerData” function when we initialise our DataTable.

(function() {

    var helpers = (function() {
    });

    helpers.formatDataTableData = function(aoData) {
        var r = {};
        var x;
        for (x in aoData) {
            r[aoData[x].name] = aoData[x].value
        }
        return { tableParams: r };
    }



    window.helpers = helpers;
})();

$('#partSearchResults').dataTable({
            "bServerSide": true,
            "sAjaxSource": 'PartSearch.aspx/GetData',
            "fnServerData": function(sSource, aoData, fnCallback) {
                $.ajax({
                    type: "POST",
                    contentType: "application/json; charset=utf-8",
                    url: "PartSearch.aspx/Search",
                    data: JSON.stringify(helpers.formatDataTableData(aoData)),
                    dataType: "json",
                    success: function(msg) { fnCallback(msg.d) }
                });
            }
        });
[


Here we have a helper function (you can put this in another file) that creates