Monday, November 28, 2011
In the first posting (MVC and DataTables) in this series we got a simple DataTables page up and running in MVC. But we are not done yet!
It’s worth noting that there are several options you can pass to the DataTables constructor. If you want more than just the Previous/Next pagination you can pass “sPaginationType”: “full_numbers”. If you want the layout to follow your jQuery UI theme pass “bJWueryUI”: true. See http://www.datatables.net/usage/options for more details on the options DataTables supports.
So how can we prevent the FOUJUI? There are several methods, a common one is to implement a loading page which hides the table while it is being formatted, but sending thousands of records across the wire to build the table is not ideal from other aspects as well. So let’s see how we can implement some AJAX to request only the data being displayed.
We will create another action in the Home controller; I called mine ‘AJAX’. Right click and create a new view, we won’t generate or retrieve any data here so just return a basic view.
In the newly created view we need a table place holder for DataTables to work with, but this time we won’t be using the @foreach to build it out. So create the table layout as shown:
We still need to add the jQuery magic, so in the @section top add:
You will notice we have added several options to the .dataTable call, let’s examine them one by one. The bServerSide option lets DataTable know it is not responsible for processing any of the information, we are going to handle the sorting, filtering, paging in our controller. The sAjaxSource is the URL where DataTable will make its AJAX calls.
The sAjaxDataProp option lets DataTable know what JSON member to look for data in. aaData is the default, and we must ensure that our Controller matches up with this value when returning information. The bProcessing option tells DataTable to put a nice “processing” wait graphic while data is being retrieved.
The sPaginatinType tells DataTable to use number pagination navigation, not just previous next. The aoColumns defines the columns we want to display.
So far so good, everything makes sense and is pretty intuitive. Let’s move on to our controller and create the GetRecords AJAX result.
But before we get the controller working we need to handle the parameters passed by DataTables to the AJAX URL. I found a post on CodeProject (http://www.codeproject.com/KB/aspnet/JQuery-DataTables-MVC.aspx) which provided a thorough outline and even goes over multi-column sorting. If you want to explore DataTables and MVC further I suggest checking it out. One of the cool things outlined in this article was the creation of a custom class to handle parameters submitted by DataTables to an AJAX URL. So create a new model class with the following:
Jovon Popovic commented this class well, so there is not much to add here. Let’s start on our Controller. Open up the Home controller and add a new ActionResult: