Using Datatables.net JQuery Plug-in with WCF Services

by jmorris 17. May 2010 13:42

There are several JQuery plug-ins that provide the basic functionality of an html grid: paging, sorting, etc. In essence these plug-ins provide a consolidated display of the data and typically means of which to interact with the data (update, insert, delete, etc). I recently had the opportunity to work with the DataTables.net grid and have been very impressed.

The following post describes the steps I used to make the DataTables grid work in an ASP.NET Webforms environment using a WCF Service as an endpoint. I’ll also go over some of the pitfalls I ran into which required a bit of ‘tweaking’ to get things working smoothly. One cool thing was that for every roadblock, a workaround was quickly discovered. This is huge when investing any time or resources on any third party plug-in or control.

First up, if you are not aware of what the DataTables is, it’s a JQuery Plug-in that written by Allan Jardine. According to the DataTables website:

“DataTables is a plug-in for the jQuery Javascript library. It is a highly flexible tool, based upon the foundations of progressive enhancement, which will add advanced interaction controls to any HTML table. “

It offers a plethora of features including pagination, filtering, sorting, auto loading of data via Ajax, Fully theme-able by CSS, etc. The documentation on the DataTables website is thorough and the quality excellent. There are also forums…good stuff. Additionally DataTables is licensed dually under the GPL v2 License and the BSD license for those who inquire…

Here is an example of Datatables with built in JQuery UI theme support:

 
The WCF Service
Datatables allows you to either have client-side paging, sorting and searching, which is the default, or you can do it on the server. Doing it on the client is the simplest and easiest way to get up and running with Datatables, however you will quickly find that it leads to larger page sizes and longer initial load times as all of the data must be piped from the server before Datatables is ready.  Performing the actions on the server makes for much a much snappier and scalable UI, but it adds complexity.

In order to use a WCF service with DataTables, you have to both honor the signature that DataTables expects and the data must be returned in a format that DataTables expects. Fortunately this is relatively easy to do; you simple need to a) map the HTTP variables from the GET request and b) generate a JSON string matches a specific format.

The HTTP variables that DataTables will post are as follows:



Note that the websiteId and categoryId are custom variables and that for each column specified, additional variables will be posted for the following fields with a consecutive numerical postfix: bSearchable_0, bSearchable_1, bSearchable_2, etc.

For my example the following WCF service method was used:



Note that I only specified a subset of the parameters in the WCF method that Datatables posts with its GET request:
 

Too be honest, I do not know why Datatables sends so many (looks like one variable per option per column for most), but from the WCF service method perspective they are optional. Also, note that Datatables uses some form of Hungarian notation to qualify the variables type. While a bit confusing at first, it did help a bit when debugging. The variables that we did specify in the WCF service method signature will be used for sorting, filtering, paging, etc.

Datatables expects to receive a JSON object with a two dimensional array called “aData” from this service. Here is an example of the server output that Datatables will receive:
 


Where “d” is the wrapper type appended by WCF and from the Datatables website:

 

Basically, note that the service must correctly compute and return the “iTotalRecords”, “iTotalDisplayRecords” and the data in “aaData”. Also, the length of each data returned must match the DataTables jQuery definition provided on the web page where the data will be displayed.

Here is the complete code listing for the internals of the WCF service method:


 

Note that depending your architecture, this code may look considerable different. However the steps are same:

  1. Query the datastore based upon the passed in parameters
    1. Calculated paging values
    2. Column to search by
    3. Column to sort by
  2. Create a JSON return result matching the JSON structure defined above.

Another thing to note here is that Datatables does not send column names; it sends the ordinal of the column with respect to the table. In order to sort by a column or filter by a column, you need to resolve the ordinal to a column name of your datastore:

 

The GetSortFieldFormOrder(int order) returns a string column name based upon the ordinal of the column so that the datastore (in this case via a sproc call) can sort the data by the correct column.

The Convert(object record) method makes an array from the values of properties of an object: each becomes an “aaData” record that is returned and used by Datatables on the client.

Just an architecture note here: in my opinion there is too much “busy” work going on here at the service level. Ideally this will be refactored into your entities so that the behavior is encapsulated outside of your data “delivery”.

The Client Code
The client JQuery code for Datatables can be very simple or rather complex depending upon the formatting and features your situation requires. Below you will see the code that I used and I will explain the major initialization required for using Datatables with a WCF service.

 

Lines 4-6 I get a reference to the DOM element I will load into using a typical JQuery selector. Let me explain the relevant settings:

A.    I am using the Datatables built in support for JQuery UI Themes
B.    I am setting the “bServerSide” flag to true so that Datatables will use AJAX to get the data source
C.    The URL of the AJAX method to call for loading data
D.    Since I want to set some custom variables to post to my service method and I want to override the default HTTP POST method that Datatables uses for invoking the AJAX method, I am overriding the “fnServerData” callback with a custom implementation.
E.    Datatables uses POST be default, I overridden the AJAX method to use a GET
F.    The results from the server are then passed into the fnCallBack callback and Datatables can now render the results.

The target for the selector is a div element on an ASP.NET UserControl:

 

   kick it on DotNetKicks.com

Tags: , , ,

Comments (52) -

Shun
Shun Mexico
5/26/2010 11:47:39 AM #

Great!!... Could you post the source code to download??

Reply

paul mungai
paul mungai Kenya
9/27/2010 10:48:13 PM #

Hi,

Thanks for your post.

Question: How do you add the 'edit' column? Looking forward to your response.

Thanks.

Reply

jmorris
jmorris United States
9/28/2010 10:38:03 PM #

@paul - you provide a "fnRowCallback" function:

var oTable;
      $(document).ready(function() {
        oTable = $('#tblBlogs').dataTable({
          "bJQueryUI": true,
          "sPaginationType": "full_numbers",
          "bProcessing": true,
          "bServerSide": true,
          "bAutoWidth": false,
          "fnRowCallback": function(nRow, aData, iDisplayIndex) {
              /* Create a link edit mode */
                  $('td:eq(0)', nRow).html('<a href="/blog/edit/' + aData[0] + '">Edit</a>');
              return nRow;
          },

          "aoColumns": [
          { "sTitle": "Id", "bVisible": true, "sClass": "center" },
          { "sTitle": "Title" },
          { "sTitle": "IsPublished", "sWidth": "125px", "sClass": "center" },
          { "sTitle": "CreatedOn", "sWidth": "125px", "sClass": "center" },
          { "sTitle": "CreatedBy", "sWidth": "125px"}],
          "sAjaxSource": '<%=Url.Action("ListData","Blog")%>'
        });
      } );

I am planning an updated post to show DataTables and ASP.NET MVC, in that post I'll go over some of the more advanced scenarios such as this.

Reply

paul mungai
paul mungai Kenya
9/28/2010 11:17:52 PM #

Hi Morris,

Thanks for your prompt response.

BTW, I'm using ASP.NET MVC, - it works Smile

Regards,
Paul.

Reply

Dave Robbins
Dave Robbins United States
1/14/2011 9:06:50 AM #

Jeff,

You might be interested in my updates to the paging solution I wrote about at Christmas.  I figured how to allow DataTables.Net to dynamically select the columns / properties from the underlying IQueryable class.  There's also a feature that allows you exclude custom client side columns from search and sort, so you can create an Actions column with href's without interfering the server-side processing.

Here's the link:

activeengine.wordpress.com/.../

Reply

jmorris
jmorris United States
1/14/2011 1:20:09 PM #

Thanks dave, i'll check it out!

Reply

Dave Robbins
Dave Robbins United States
2/9/2011 6:24:16 PM #

Yet another update to the paging solution for DataTables.Net.  I've added support for multi-column sorting.  I'm glad you guys are finding this useful!!

activeengine.wordpress.com/.../

Reply

ebay selling
ebay selling United States
2/25/2011 6:49:36 PM #

Hi Dave
In your example you are working with JQuery editor
can you please share which one it is.

Reply

Istria Croatia
Istria Croatia United States
3/9/2011 3:57:47 AM #

Great article about jquery, this is what i need! thanks!

Reply

authority formula bonus
authority formula bonus United States
3/11/2011 4:20:26 AM #

JQuery beginner and this info has been most helpful.

Reply

Kentucky Web Designer
Kentucky Web Designer United States
3/11/2011 11:09:56 AM #

I'm just now starting to understand JQuery..thanks for the info

Reply

Kućni ljubimci
Kućni ljubimci Croatia
3/13/2011 9:48:30 AM #

Wonderful article about jQuery!

Reply

Beth Paparone
Beth Paparone United States
3/14/2011 12:32:34 PM #

Hey this is Beth Paparone from Window Design for you. I think this plugin would work prefect for my site. Thanks!

Reply

webdesigner
webdesigner United States
3/31/2011 6:12:55 AM #

this is an amazing article,things put together perfect..i would like to thank you for that

Reply

garage door repair houston
garage door repair houston United States
3/31/2011 7:01:07 PM #

I agree. Wonderful article about jQuery!

Reply

jason robertson
jason robertson Australia
4/12/2011 4:16:49 AM #

source would be great works in the asmx examples and MVC example on Code Project this is the only post on the web re WCF also .NET 3.5

Reply

jeff
jeff United States
4/22/2011 8:44:25 PM #

A couple of people have asked for the source, I'll try to post it sometime soon.

Reply

Darren Brown
Darren Brown United States
4/22/2011 8:29:38 PM #

You mentioned that Datatables uses Hungarian notation for the variable types.  That sounds rather confusing to work with.  Any idea as to how or why it's made this way?  I assume it must be from a Hungarian development team, right?

Reply

jason robertson
jason robertson Australia
4/30/2011 12:24:20 AM #

OK I got this working but having used WCF in the past with the .NET Microsoft AJAX library and not jQuery and also having the contstraints of SP2010 it was an 18 round punch on meaning it threw 18 different errors or at least 18 times and took a few hours clearly learning curve on WCF in the context of JQuery and SharePoint Notice this is the GET still working on the POST. Also this is just jQuery and WCF SharePoint another day. Key point is that you will need to use the web.config settings approach in a SharePoint context (I believe at this point). This post from Rick Strahl helped a lot http://www.west-wind.com/WebLog/posts/310747.aspx . For SharePoint more specifically see Salim Maleks WinSmarts site his book is good also or Chris Obriens Posts, many ways to skin the cat I have a focus to use Silverlight and JQuery on the same services and WCF is the future or the now for now so I would not waste time on what is the past and also the learning or knowledge domain is more valuable in my opinion around WCF.

The web.config is or can be tricky to get right my service and classes are in the namespace of DataGrid being the class namespace not the WCF Interface it is unmarked in terms of a namespace attribute as per Jeffs post no namespace arrtibute on the service. Another point is using this in the service. It may be possible to get this working with a host factory like Factory="System.ServiceModel.Activation.WebServiceHostFactory" but that was not my starting point due to my needs. Any way hope this helps someone. Passing the parameters is ok I want to pass the full JSON and all the DataTables .NET grid parameters as JSON and when I solve this I will post the code on Code Project probably tonight

<system.serviceModel>
  <behaviors>  
   <serviceBehaviors>
    <behavior name="DataGrid.ArticleListServiceBehavior">
     <serviceMetadata httpGetEnabled="true" />
     <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
    <behavior name="DataGrid.Service1Behavior">
     <serviceMetadata httpGetEnabled="true" />
     <serviceDebug includeExceptionDetailInFaults="true" />
    </behavior>
   </serviceBehaviors>
      <endpointBehaviors>
          <behavior name="DataGrid.ArticleListServiceBehavior">
              <webHttp/>
          </behavior>
          <behavior name="DataGrid.Service1Behavior">
              <webHttp/>
          </behavior>
      </endpointBehaviors>
  </behaviors>
     <services>
         <service behaviorConfiguration="DataGrid.ArticleListServiceBehavior" name="DataGrid.ArticleListService">
             <endpoint address="" binding="webHttpBinding" contract="DataGrid.IArticleListService" behaviorConfiguration="DataGrid.ArticleListServiceBehavior">                
             </endpoint>            
         </service>
        
         <service behaviorConfiguration="DataGrid.Service1Behavior" name="DataGrid.Service1">
             <endpoint address="" binding="webHttpBinding" contract="DataGrid.IService1" behaviorConfiguration="DataGrid.Service1Behavior">                
             </endpoint>            
         </service>
     </services>
</system.serviceModel>

Reply

jason robertson
jason robertson Australia
4/30/2011 12:37:14 AM #

While I am here I can't resist commenting on the Hungarian notation its a coding style can't remember why its called that but it involves type names in variables Camel case and other coding styles to help make code easier to maintain and read. If you have ever dealt with code that resuses the same variable with differnet types in the variable at different points in the code and other spaghetti coding approaches or worked on large scale apps this sort of discipline can make life easier. Even when you revisit your own code heaven forbid there are bugs that you have to fix the next year or months after you coded it which can happen onn large projects

Reply

aromaterapija
aromaterapija Croatia
9/2/2011 5:30:06 AM #

Thanks for your post!!!

Reply

Judgments
Judgments United States
11/17/2011 7:13:29 PM #

You actually select amazing themes for all of your posts within the journal. I would most likely really like to come again here for likewise good articles or blog posts.

Reply

Fast Way Lose Weight
Fast Way Lose Weight United States
11/18/2011 7:20:20 AM #

Thanks for writing this post on using datatables.net jquery plug-in.

And thanks especially for the code examples - they were really helpful in following the article!

Reply

iwowwetoo
iwowwetoo
11/19/2011 1:04:47 AM #

Congratulations! We are giving away 100 MLM free leads to you today, so hurry and get your leads here. http://worldmarketleads.com

If I need any thing else let me know.

Reply

Technology Blog
Technology Blog
11/19/2011 3:06:13 AM #

Simply wish to say your article is as surprising. The clearness in your post is just excellent and i could assume you\'re an expert on this subject. Well with your permission allow me to grab your feed to keep up to date with forthcoming post. Thanks a million and please continue the enjoyable work.  Thanks !

Reply

john
john
11/20/2011 12:16:16 AM #

Hi ,

Great post, it gives me good info. Thanks for sharing.

Reply

You actually select amazing themes for all of your posts within the journal. I would most likely really like to come again here for likewise good articles or blog posts.

Reply

Technology Blog
Technology Blog
11/22/2011 9:04:15 AM #

Just desire to say your article is as surprising. The clearness in your post is simply great and i could assume you\'re an expert on this subject. Well with your permission let me to grab your RSS feed to keep updated with forthcoming post. Thanks a million and please continue the enjoyable work.  Thanks !

Reply

wordpress templates
wordpress templates
11/25/2011 12:01:44 AM #

Hey  you actually make it seem really easy along with your presentation however I in finding this link to be actually something that I feel I would by no means understand. It sort of feels too complicated and very vast for me. I am taking a look forward in your subsequent put up, I\'ll try to get the cling of it!

Reply

Daily Deals
Daily Deals Australia
11/26/2011 9:58:42 PM #

Nice information, many thanks to the author. It is incomprehensible to me now, but in general, the usefulness and significance is overwhelming. Thanks again and good luck!

Reply

Online Clothes Shopping Australia
Online Clothes Shopping Australia Australia
11/26/2011 10:00:01 PM #

Thanks for taking the time to discuss this, I feel strongly about it and love learning more on this topic. If possible, as you gain expertise, would you mind updating your blog with more information? It is extremely helpful for me.

Reply

wedding garters
wedding garters United Kingdom
11/28/2011 6:56:53 PM #

where would some one start to learn j query? i have some on my website thast i would like to tweek but dont know how, do you have any good resources

Reply

StrongJoe
StrongJoe
12/8/2011 3:08:22 AM #

,


Thanks a lot pertaining to this particular writeup titled Rantdriven.com today I had been speaking with my pals relating to this topic and for the most part We totally agree as to what you are saying.  I have already been speaking about this kind of subject a whole lot of late with our friends so with some luck it will help me make my point.

I would like to make a request and that is that it would be great if you could go into a little more detail.  Or maybe you can actually point us to some additional websites where we could get more information.

By the way, I am wondering if you have come across anything with regards to MUFAs (Mono Unsaturated Fatty Acids).  If so then can you please publish an article about it?

Reply

awm
awm Australia
12/8/2011 7:19:33 PM #

Very fascinating! Great post!. A comprehensive roundup of all the good sources I already knew of and few I didn’t. I am always looking for new ways to make my site more useful to my users. Thanks for your kind consideration to help us improve our service. Thanks a bunch.

Reply

a.antoinette
cheap web hosting
12/9/2011 6:49:33 AM #

Thanks  for the awesome share.
A friend of mine advised this site. And yes. it has some useful pieces of information and I enjoyed reading it.

Reply

hostgator hosting
hostgator hosting
12/9/2011 6:50:26 AM #

Thanks  for the amazing share.
nice post, will be great to see more like this

Reply

square shade sails
square shade sails United States
12/19/2011 9:07:45 AM #

I enjoyed reading this. It isn't something very astonishing, on the other hand this is fine. Moreover, danke for letting us know. Continue writing instructive posts

Reply

credit report disputes
credit report disputes United States
12/19/2011 6:32:06 PM #

Very useful information and great help to complete my assignment on time. Thanks buddy.

Reply

luxuria
luxuria United States
12/23/2011 1:08:55 AM #

An interesting discussion is worth comment. I think that you should write more on this topic, it might not be a taboo subject but generally people are not enough to speak on such topics. To the next. Cheers

Reply

Linda
Linda Netherlands
12/23/2011 4:34:53 AM #

I found this very informative , unlike the majority of the other fake comments here! Thanks!

Reply

Vakantiehuis
Vakantiehuis Netherlands
12/23/2011 4:37:03 AM #

Hear Hear. Well worth the time to read this in-depth. Kudos!

Reply

Lichtkranten
Lichtkranten Netherlands
12/24/2011 2:02:15 AM #

Thanks for this share! This will be very usefull for me...

Kind Regards,

Anne Lichtkranten

Reply

Prinsessenjurk
Prinsessenjurk Netherlands
12/24/2011 2:03:21 AM #

I really love JQuery!!!

Reply

Nordicwalkingspecialist
Nordicwalkingspecialist Netherlands
12/24/2011 3:45:26 AM #

Great article. Thanks for the information.

Kind Regards,

Hans

Reply

Skelters4you
Skelters4you Netherlands
12/24/2011 3:49:40 AM #

Great article about jquery.



Reply

Trampolines4you
Trampolines4you Netherlands
12/24/2011 3:56:01 AM #

What a wonderful article about jQuery! Thank you.

Reply

Facebook Closing
Facebook Closing United States
12/24/2011 6:55:28 AM #

Nice work. Your post helped me a lot. Thanks! Got you bookmarked for furure reference.

Reply

Fietsen
Fietsen Netherlands
12/24/2011 7:41:24 AM #

Very impressed. Thank you so much for this article. I will forward this story.

Reply

Gale
Gale
1/3/2012 2:50:50 AM #

Pretty cool site. I\\\'ve looked around and haven\\\\\\\'t seen one much better.

Reply

Erwin
Erwin
1/4/2012 12:38:45 AM #

Decently bad A topic. I\\\'ve looked all over and haven\\\\\\\'t found one a lot nicer.

Reply

HD Movies
HD Movies United States
1/5/2012 8:48:54 AM #

The world crop of coco beans was not very good this year and to see the wanton waste of these dwindling resources just makes me want to weep. About a week. Less if that's honest-to-god white chocolate.

Reply

Rob
Rob
1/14/2012 3:00:21 PM #

It always amazes me how much Social Media websites has an impact on the amount of traffic that you can get when done properly

Keep up the great work,

Robert

Reply

Pingbacks and trackbacks (6)+

Add comment

  Country flag

biuquote
  • Comment
  • Preview
Loading

Who Am I?

My name is Jeff Morris a software engineer/developer in Southern California, USA. My platform du jour is dotnet, but I dabble on the darkside occasionally.

Tag cloud

Month List

Page List