I am using the JQuery Datatables plugin in an ASP.NET MVC project to display some tabular data, which is in turn taken from a database using Entity Framework.
I have configured the Datatable to use ajax search and sort routines, and I am using an extension method to allow me to specify the name of a column to be sorted as a string. This works perfectly for most fields, but I get an error when trying to sort a field that contains a DateTime object.
View JQuery Code:
$('#Orders').dataTable({
"bServerSide": true,
"sAjaxSource": "/Suppliers/GetOrders/@Model.ID",
"aaSorting": [[1, 'desc']],
"bProcessing": true,
bAutoWidth: false,
"sPaginationType": "full_numbers",
"aoColumns": [
{ "bVisible": false },
{ "sName": "OrderNumber",
"bSearchable": false,
"bSortable": true,
"fnRender": function (oObj) {
return '<a href=\"/Orders/View/' + oObj.aData[0] + '\">' + oObj.aData[1] + '</a>';
}
},
{ "sName": "Supplier", "bSortable": true },
{ "sName": "Client" },
{ "sName": "OrderPlaced" },
{ "sName": "OrderReceived"},
{ "sName": "OrderedBy" },
{ "sName": "Actions",
"fnRender": function (oObj) {
return '<a href=\"/Orders/View/' + oObj.aData[0] + '\">view</a>';
}
}
]
});
Controller code:
var data = DataContext.PartsOrders.Select(order =>
new {
order.SupplierID,
order.UniverseID,
order.ID,
order.OrderNumber,
Supplier = order.Supplier.Name,
Client = order.Job.Client.Name,
DateOrderPlaced = order.DateOrderPlaced,
order.DateOrderReceived,
OrderedBy = order.OrderedBy.Name
}).Where(x => x.SupplierID == id && x.UniverseID == Universe.ID);
data = data.OrderByField(columnNames[Convert.ToInt32(Request["iSortCol_0"])], Request["sSortDir_0"]);
And my ExtensionMethod is as follows, based on some code I found online. I'm not entirely sure I understand what this code is doing, which doesnt help me find my problem!
public static IQueryable<T> OrderByField<T>(this IQueryable<T> q, string SortField, string SortDirection)
{
var param = Expression.Parameter(typeof(T), "p");
var prop = Expression.Property(param, SortField);
var exp = Expression.Lambda(prop, param);
string method = "";
if (SortDirection == "asc")
method = "OrderBy";
else
method = "OrderByDescending";
Type[] types = new Type[] { q.ElementType, exp.Body.Type };
var mce = Expression.Call(typeof(Queryable), method, types, q.Expression, exp);
return q.Provider.CreateQuery<T>(mce);
}
Finally, the error I get when trying to sort a column containing a date:
Instance property 'OrderPlaced' is not defined for type '<>f__AnonymousType6`9[System.Nullable`1[System.Int32],System.Int32,System.Int32,System.String,System.String,System.String,System.Nullable`1[System.DateTime],System.Nullable`1
this occurs in the extension method, on line var prop = Expression.Property(param, SortField);