I'm attempting to do server-side processing of jQuery DataTables using ASP.NET MVC with Entity Framework. I came across Datatables.AspNet Nuget package, but I'm unclear how to use it to dynamically sort columns when clicked on table headers.
In an example on Datatables.AspNet GitHub, there is this:
public ActionResult PageData(IDataTablesRequest request)
{
var data = Models.SampleEntity.GetSampleData();
var filteredData = data.Where(_item => _item.Name.Contains(request.Search.Value));
// Paging filtered data.
var dataPage = filteredData.Skip(request.Start).Take(request.Length);
var response = DataTablesResponse.Create(request, data.Count(), filteredData.Count(), dataPage);
return new DataTablesJsonResult(response, JsonRequestBehavior.AllowGet);
}
But I'm unsure how to proceed to dynamically sort based on the contents of the IDataTablesRequest object, which looks like this:
public interface IDataTablesRequest
{
int Draw { get; }
int Start { get; }
int Length { get; }
ISearch Search { get; }
IEnumerable<IColumn> Columns { get; }
IDictionary<string, object> AdditionalParameters { get; }
}
public interface ISort
{
int Order { get; }
SortDirection Direction { get; }
}
public enum SortDirection
{
Ascending = 0,
Descending = 1
}
take a look at this answer: https://github.com/ALMMa/datatables.aspnet/issues/26
for reference:
public static IQueryable<T> OrderBy<T>(this IQueryable<T> source, IEnumerable<DataTables.AspNet.Core.IColumn> sortModels)
{
var expression = source.Expression;
int count = 0;
foreach (var item in sortModels)
{
var parameter = Expression.Parameter(typeof(T), "x");
var selector = Expression.PropertyOrField(parameter, item.Field);
var method = item.Sort.Direction == DataTables.AspNet.Core.SortDirection.Descending ?
(count == 0 ? "OrderByDescending" : "ThenByDescending") :
(count == 0 ? "OrderBy" : "ThenBy");
expression = Expression.Call(typeof(Queryable), method,
new Type[] { source.ElementType, selector.Type },
expression, Expression.Quote(Expression.Lambda(selector, parameter)));
count++;
}
return count > 0 ? source.Provider.CreateQuery<T>(expression) : source;
}
so you can do the following:
var orderColums = request.Columns.Where(x => x.Sort != null);
var dataPage = data.OrderBy(orderColums).Skip(request.Start).Take(request.Length);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With