Skip to content

Instantly share code, notes, and snippets.

@csainty
Created March 22, 2012 00:50
Show Gist options
  • Save csainty/2154832 to your computer and use it in GitHub Desktop.
Save csainty/2154832 to your computer and use it in GitHub Desktop.
Table query wrapper
[NonAction]
protected ActionResult WrapDataTableQuery<T>(IQueryable<T> data, Func<string, Expression<Func<T, bool>>> filter, Func<IQueryable<T>, string, bool, IOrderedQueryable<T>> applyOrderingFunction, Func<T, object[]> decorator)
{
// Fetch query parameters from the form buffer. All queries are POSTs
var queryData = ParseDataTableQueryDetails();
if (!String.IsNullOrWhiteSpace(queryData.SearchTerm))
{
data = data.Where(filter(queryData.SearchTerm.ToLower()));
}
int querytotal = data.Count();
data = applyOrderingFunction(data, queryData.SortColumnName, queryData.SortAscending); // Find our order by clause and apply it
data = data.Skip(queryData.Skip).Take(queryData.Take); // Perform paging of data
// The data is now materialized, sending the query to the server, until now we were just query building
var results = data.ToArray().Select(d => decorator(d)); // Process each database row into the decorated rows we want to return
// Build up the expected result object and return as json
dynamic result = new
{
sEcho = queryData.Echo,
iTotalRecords = querytotal,
iTotalDisplayRecords = querytotal,
aaData = results.ToArray()
};
return Json(result);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment