Using Datatables.net JQuery Plug-in with WCF Services

by jmorris 17. May 2010 22: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

5/26/2010 8:47:39 PM #

Shun

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

Shun Mexico | Reply

7/20/2010 3:44:21 AM #

pingback

Pingback from mdavey.wordpress.com

Will HTML5 Take Over The World? « Tales from a Trading Desk

mdavey.wordpress.com | Reply

7/29/2010 9:18:52 PM #

trackback

Using Datatables.net JQuery Plug-in with WCF Services

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com | Reply

9/28/2010 7:48:13 AM #

paul mungai

Hi,

Thanks for your post.

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

Thanks.

paul mungai Kenya | Reply

9/29/2010 7:38:03 AM #

jmorris

@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.

jmorris United States | Reply

9/29/2010 8:17:52 AM #

paul mungai

Hi Morris,

Thanks for your prompt response.

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

Regards,
Paul.

paul mungai Kenya | Reply

12/20/2010 4:56:39 AM #

pingback

Pingback from activeengine.wordpress.com

How to Create Server-Side Paging for DataTables.Net with ASP.Net « ActiveEngine

activeengine.wordpress.com | Reply

1/14/2011 6:06:50 PM #

Dave Robbins

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/.../

Dave Robbins United States | Reply

1/14/2011 10:20:09 PM #

jmorris

Thanks dave, i'll check it out!

jmorris United States | Reply

2/10/2011 3:24:16 AM #

Dave Robbins

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/.../

Dave Robbins United States | Reply

2/26/2011 3:49:36 AM #

ebay selling

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

ebay selling United States | Reply

3/9/2011 12:57:47 PM #

Istria Croatia

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

Istria Croatia United States | Reply

3/11/2011 1:20:26 PM #

authority formula bonus

JQuery beginner and this info has been most helpful.

authority formula bonus United States | Reply

3/11/2011 8:09:56 PM #

Kentucky Web Designer

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

Kentucky Web Designer United States | Reply

3/13/2011 6:48:30 PM #

Kućni ljubimci

Wonderful article about jQuery!

Kućni ljubimci Croatia | Reply

3/14/2011 9:32:34 PM #

Beth Paparone

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

Beth Paparone United States | Reply

3/31/2011 3:12:55 PM #

webdesigner

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

webdesigner United States | Reply

4/1/2011 4:01:07 AM #

garage door repair houston

I agree. Wonderful article about jQuery!

garage door repair houston United States | Reply

4/12/2011 1:16:49 PM #

jason robertson

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

jason robertson Australia | Reply

4/23/2011 5:44:25 AM #

jeff

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

jeff United States | Reply

4/23/2011 5:29:38 AM #

Darren Brown

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?

Darren Brown United States | Reply

4/29/2011 11:51:31 PM #

trackback

Using Datatables.net JQuery Plug-in with WCF Services part Duex

Using Datatables.net JQuery Plug-in with WCF Services part Duex

Rantdriven.com | Reply

4/30/2011 9:24:20 AM #

jason robertson

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>

jason robertson Australia | Reply

4/30/2011 9:37:14 AM #

jason robertson

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

jason robertson Australia | Reply

7/29/2011 6:48:18 PM #

pingback

Pingback from itanil.com

Data Points: Slice and Dice OData with the jQuery DataTables Plug-In « ITANIL-Technology Information

itanil.com | Reply

9/2/2011 2:30:06 PM #

aromaterapija

Thanks for your post!!!

aromaterapija Croatia | Reply

11/18/2011 4:13:29 AM #

Judgments

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.

Judgments United States | Reply

11/18/2011 4:20:20 PM #

Fast Way Lose Weight

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!

Fast Way Lose Weight United States | Reply

11/19/2011 10:04:47 AM #

iwowwetoo

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.

iwowwetoo | Reply

11/19/2011 12:06:13 PM #

Technology Blog

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 !

Technology Blog | Reply

11/20/2011 9:16:16 AM #

john

Hi ,

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

john | Reply

11/22/2011 11:59:13 AM #

mother of the bride dresses with jackets

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.

mother of the bride dresses with jackets United States | Reply

11/22/2011 6:04:15 PM #

Technology Blog

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 !

Technology Blog | Reply

11/25/2011 9:01:44 AM #

wordpress templates

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!

wordpress templates | Reply

11/27/2011 6:58:42 AM #

Daily Deals

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!

Daily Deals Australia | Reply

11/27/2011 7:00:01 AM #

Online Clothes Shopping Australia

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.

Online Clothes Shopping Australia Australia | Reply

11/29/2011 3:56:53 AM #

wedding garters

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

wedding garters United Kingdom | Reply

12/8/2011 12:08:22 PM #

StrongJoe

,


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?

StrongJoe | Reply

12/9/2011 4:19:33 AM #

awm

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.

awm Australia | Reply

12/9/2011 3:49:33 PM #

a.antoinette

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.

cheap web hosting | Reply

12/9/2011 3:50:26 PM #

hostgator hosting

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

hostgator hosting | Reply

12/19/2011 6:07:45 PM #

square shade sails

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

square shade sails United States | Reply

12/20/2011 3:32:06 AM #

credit report disputes

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

credit report disputes United States | Reply

12/23/2011 10:08:55 AM #

luxuria

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

luxuria United States | Reply

12/23/2011 1:34:53 PM #

Linda

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

Linda Netherlands | Reply

12/23/2011 1:37:03 PM #

Vakantiehuis

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

Vakantiehuis Netherlands | Reply

12/24/2011 11:02:15 AM #

Lichtkranten

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

Kind Regards,

Anne Lichtkranten

Lichtkranten Netherlands | Reply

12/24/2011 11:03:21 AM #

Prinsessenjurk

I really love JQuery!!!

Prinsessenjurk Netherlands | Reply

12/24/2011 12:45:26 PM #

Nordicwalkingspecialist

Great article. Thanks for the information.

Kind Regards,

Hans

Nordicwalkingspecialist Netherlands | Reply

12/24/2011 12:49:40 PM #

Skelters4you

Great article about jquery.



Skelters4you Netherlands | Reply

12/24/2011 12:56:01 PM #

Trampolines4you

What a wonderful article about jQuery! Thank you.

Trampolines4you Netherlands | Reply

12/24/2011 3:55:28 PM #

Facebook Closing

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

Facebook Closing United States | Reply

12/24/2011 4:41:24 PM #

Fietsen

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

Fietsen Netherlands | Reply

1/3/2012 11:50:50 AM #

Gale

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

Gale | Reply

1/4/2012 9:38:45 AM #

Erwin

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

Erwin | Reply

1/5/2012 5:48:54 PM #

HD Movies

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.

HD Movies United States | Reply

1/15/2012 12:00:21 AM #

Rob

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

Rob | Reply

1/16/2012 2:36:55 PM #

Jennie

Be quick rich with this  Great software. It has changed my life now and forever
http://richersucess.com

Jennie | Reply

1/17/2012 3:45:14 AM #

carpet cleaning marsden

Hey  I really love your blog, it is full amazing information.  I hope you don\'t mind me sharing it with my Facebook community.

carpet cleaning marsden United States | Reply

1/31/2012 6:38:41 PM #

pingback

Pingback from tvlinksalternatives.rapidride.info

Giants vs. Patriots II: Does 2008 matter?
    (AP) | Tv Links Alternatives

tvlinksalternatives.rapidride.info | Reply

2/3/2012 11:58:25 PM #

license music games

Ratigan does not say just what Geithner should have done, because Ratigan does not have any idea what Geithner or anyone else in authority should have done to stop the disaster  or when they should have done it.listen to new song

license music games United States | Reply

Add comment


(Will show your Gravatar icon)

  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

Page List