Welcome to weblogs.com.pk Sign in | Join | Help

ASP.NET-DataTables with WebApi

In the previous post, we couldn’t handle DataTables’ Paging, Sorting and Searching at the Server Side due to PageMethods limitations. There might be some work-around, but we had another requirement that we had to implement our thing in ASCX (User Control) and not in ASPX page and unfortunately PageMethods don’t work in ASCXes; but fortunately we have WebApi!

There is a misconception that WebApi can only be used with Visual Studio 2012 / ASP.NET 4.5; this is not true, WebApi v1 was made available along MVC4 (and WebApi v2 with MVC5); MVC4 works and is supported on VS2010SP1 and installing MVC4 tooling for Visual Studio 2010; you can use WebApi just fine

To setup your project for WebApi; I will suggest to use IISExpress and adding required system.webServer/handlers; these handler entries ensure that all requests are being handled by ASP.NET. You will need few Microsoft.AspNet.WebApi* NUGET packages along with Microsoft.Net.Http and optionally Newtonsoft.Json package. If you are on Visual Studio 2012 or later; the quickest way is using Add New Item dialog and adding Web Api Controller class, IDE takes care of all the things. I havnt checked on Visual Studio 2010 but I am sure after adding MVC4 tooling there must be similar option and behavior there, I am also attaching screenshot of relevant settings just in case! You can see, we are still targeting .NET4 and project is still open able in Visual Studio 2010 (with SPI1 and other required tools like NUGET, MVC4 etc)

image

Using Fiddler or F12 Developer Tools in the browser if you view the network traffic, you can easily breakdown what DataTables plugin is sending to the server. If we reverse engineer that; we will end up writing the following Api Controller

image

Note how search and order parameters are decorated with [FromUri], doing so we can have the values auto-magically parsed from the querystring into our Api Controller method. Also note the use of dynamic type as return type; in WebApi instead of writing the JSON into the Response, we can return it as a typed object. The beauty of Dynamic Languages and richness of the Typed Language!

Here is the Get() code snippet for the proof of concept

Code Snippet
  1. //http://datatables.net/manual/server-side
  2. public dynamic Get(int draw, int start, int length,
  3.     [FromUri]Search search = null, [FromUri]Order[] order = null)
  4. {
  5.     IEnumerable<Note> list = getList(100);
  6.     //searching
  7.     if (null != search && !string.IsNullOrEmpty(search.value))
  8.         list = list.Where(n => n.Description.Contains(search.value));
  9.     //sorting
  10.     IOrderedEnumerable<Note> orderedList;
  11.     if (null != order && order.Length > 0 && order[0].column > 0)
  12.     {
  13.         Func<Note, object> f = note => order[0].column == 0
  14.             ? (object)note.NoteID : note.Description;
  15.         if (!string.IsNullOrEmpty(order[0].dir) && order[0].dir == "desc")
  16.             orderedList = list.OrderByDescending(f);
  17.         else
  18.             orderedList = list.OrderBy(f);
  19.     }
  20.     else
  21.         orderedList = list.OrderBy(n => n.NoteID);
  22.     //http://datatables.net/manual/server-side
  23.     var result = new
  24.     {
  25.         draw = draw,
  26.         recordsTotal = orderedList.Count(),
  27.         recordsFiltered = orderedList.Count(),
  28.         data = orderedList.Select(o => new[] { o.NoteID.ToString(), o.Description })
  29.         .Skip(start).Take(length),  // Paging
  30.         error = string.Empty
  31.     };
  32.  
  33.     return result;
  34. }

In the Gobal.asax we need to register the Web API routes

Code Snippet
  1. void Application_Start(object sender, EventArgs e)
  2. {
  3.     RouteTable.Routes.MapHttpRoute(name: "API Default",
  4.         routeTemplate: "api/{controller}/{id}",
  5.         defaults: new { id = RouteParameter.Optional });
  6. }

If we register ours with the above code; we can access it at /api/DataTables

image

Note the use of GET type and not POST, if we write a parameter less GET method in our Api Controller we can test it using plain browser as well!

Bonus Tip

If you are doing this all for some enterprise app where many people still uses older version of IE or IE with Compatibility Mode on (by default) for Intranet Zone, your new CSS things might not work. Explaining and getting things changed at all machines might not be convenient. By adding Response.AddHeader(“X-UA-Compatible”, “IE=Edge”), (IE=Edge or IE=10 etc) you can set compatibility mode at server side and your things will render using the latest rendering engine in recent versions of IE!

You can add <meta> tag for this as well; if you have control on the Master Page or Skin in the CMS etc, read http://blogs.msdn.com/b/cjacks/archive/2012/02/29/using-x-ua-compatible-to-create-durable-enterprise-web-applications.aspx for complete details!

Published Thursday, August 27, 2015 11:49 AM by khurram
Filed under: ,

Comments

No Comments

New Comments to this post are disabled