Problem:
- jQuery DataTables server-side processing using ASP.NET WebForms.
Solution:
- Darin Dimitrov answered the question using an example which pages and sorts, but doesn't do any searching. Here's my **basic** modification of his work to make searching work on his example:
public class Data : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
// Paging parameters:
var iDisplayLength = int.Parse(context.Request["iDisplayLength"]);
var iDisplayStart = int.Parse(context.Request["iDisplayStart"]);
// Sorting parameters
var iSortCol = int.Parse(context.Request["iSortCol_0"]);
var iSortDir = context.Request["sSortDir_0"];
// Search parameters
var sSearch = context.Request["sSearch"];
// Fetch the data from a repository (in my case in-memory)
var persons = Person.GetPersons();
// Define an order function based on the iSortCol parameter
Func<Person, object> order = person => iSortCol == 0 ? (object) person.Id : person.Name;
// Define the order direction based on the iSortDir parameter
persons = "desc" == iSortDir ? persons.OrderByDescending(order) : persons.OrderBy(order);
// prepare an anonymous object for JSON serialization
var result = new
{
iTotalRecords = persons.Count(),
iTotalDisplayRecords = persons.Count(),
aaData = persons
.Where(p => p.Name.Contains(sSearch)) // Search: Avoid Contains() in production
.Where(p => p.Id.ToString().Contains(sSearch))
.Select(p => new[] {p.Id.ToString(), p.Name})
.Skip(iDisplayStart) // Paging
.Take(iDisplayLength)
};
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(result);
context.Response.ContentType = "application/json";
context.Response.Write(json);
}
public bool IsReusable { get { return false; } }
}
public class Person
{
public int Id { get; set; }
public string Name { get; set; }
public static IEnumerable<Person> GetPersons()
{
for (int i = 0; i < 57; i++)
{
yield return new Person { Id = i, Name = "name " + i };
}
}
}