Asp.net using JQuery Datatables 1.10 plugin and AJAX

Have you ever tried using the latest version of the datatables JQuery plugin together with ASP.net? You might get frustated!

If you are using the datatables plugin together with ASP.net MVC and don’t use any AJAX calls, you probably won’t run into any troubles. The plugin is super easy to use. To add it to your tables on your site you only need one line of JQuery:

$('table').dataTable();

You will find a pretty good examples on the datatables project website.

Datatables-JQuery-Plugin

So what’s the problem here?

If you try to use the datatables version 1.10 plugin in conjunction with AJAX it gets a little bit difficult. You might try something like this:

Javascript:

var cssRocks =	{    
	'opts':	{
		'tables':	{ 
			'ajax':	{
				'url': 'serverSideTableProviderPage',
				'type': 'POST',
			},
			'pagingType':	'simple',
			'order':		[[0,'asc']],
			'pageLength': 100,
			'columns':	{[
				'data':    'column1',
				'data':    'column2'
			]}
		}
	},
	'makeTablesAwsome':    function(opts) {
		$('table').dataTable(opts);
	}
} 
$(document).ready(function () {
    cssTricks.makeTablesAwsome(cssTricks.opts.tables);
});

C#:

namespace cssRocks.Controllers
{
    public class RockController : Controller
    {
        public ActionResult serverSideTableProviderPage()
        {
            //load the table
            
            return View(tableModel);
        }
        [HttpPost]
        public JsonResult serverSideTableProviderPage(ViewModel tableData)
        {
            //process tableData
            
            return Json(tableModel,JsonRequestBehavior.DenyGet);
        }
    }
}

namespace cssRocks.Models
{
    public class ViewModel
    {
        public IEnumerable<DTColumn> columns {get; set;}
        public int draw { get; set; }
        public int length { get; set; }
        public IEnumerable<DTOrder> order { get; set; }
        public DTSearch search { get; set; }
    }
    public class DTSearch
    {
        public bool regex {get; set;}
        public string value {get; set;}
    }
    [...]
}

What you would expect is that the data that is send to the action “serverSideTableProviderPage” and the POST parameters coming from the datatables plugin are getting mapped to the “ViewModel”.

What actually happens is that only the fields “draw” and “length” receive values. The rest of the fields – the deep nested ones- are all receiving null as value from the default ModelBinder.

What’s the source of all problems?

ASP can’t process the data that is send by the datatables plugin. The data has the followering format:


columns[0][data]            column1
columns[0][name]
columns[0][orderable]        true
columns[0][search][regex]    false
columns[0][search][value]
columns[0][searchable]        true
columns[1][data]            column2
columns[1][name]
columns[1][orderable]        true
columns[1][search][regex]    false
columns[1][search][value]
columns[1][searchable]        true
draw                        1
length                        100
order[0][column]            0
order[0][dir]                asc
search[regex]                false
search[value]
start                        0

The datatables plugin sends the POST parameters with indexes that ASP.net can’t process.

Let’s take a look at the data field search

The search field was mapped as a complex type in our model. And we can see that it has two subfields: value and regex.
But ASP.net is actually seeing two fields named “search[value]” and “search[regex]”. ASP.net doesn’t recognize the search field as field with two subfields. And that’s why our complexType search doesn’t receive any data.

 

The Solution

The solution is super simple and easy to implement. You just have to transform the data that is send by the datatables plugin to the right form. Sounds difficult? It isn’t!

Javascript:

var cssRocks =	{    
	'opts':	{
		'tables':	{ 
			'ajax':	{
				'url': 'serverSideTableProviderPage',
				'type': 'POST',
				'data':function(data)
                 {
                       return data = JSON.stringify(data);
                 }
			},
			'pagingType':	'simple',
			'order':		[[0,'asc']],
			'pageLength': 100,
			'columns':	{[
				'data':    'column1',
				'data':    'column2'
			]}
		}
	},
	'makeTablesAwsome':    function(opts) {
		$('table').dataTable(opts);
	}
} 
$(document).ready(function () {
    cssTricks.makeTablesAwsome(cssTricks.opts.tables);
});

This way, the data is send as JSON string. The rest is “magic”. Just kidding. ASP.net will notice that you are sending the data as JSON. The data will be mapped correctly to your fields in your model. Even the deep nested fields!

UPDATE
I will post a fully working example which shows how to put all this together in the next days. Having the data from DataTables in your receiving model is one step. How to query your DBModel is another problem which has to be solved. Stay tuned!

Advertisements

3 thoughts on “Asp.net using JQuery Datatables 1.10 plugin and AJAX

  1. John says:

    I’m having trouble trying to add additional param using fnServerParams that function gets called but the controller action never gets called when adding the fnServerParams statement to the code. Any ideas how to pass additional params?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s