Problème:
- Traitement côté serveur jQuery DataTables avec ASP.NET WebForms.
Solution:
- Darin Dimitrov a répondu à la question en utilisant un exemple de pages et de types, mais n'a effectué aucune recherche. Voici ma ** modification ** de base de son travail pour que la recherche fonctionne sur son exemple:
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 };
}
}
}