我在 ASP.NET MVC 项目中使用 JQuery Datatables 插件来显示一些表格数据,这些数据又是从使用实体框架的数据库中获取的。
我已将 Datatable 配置为使用 ajax 搜索和排序例程,并且我正在使用扩展方法来允许我指定要作为字符串排序的列的名称。这适用于大多数字段,但在尝试对包含 DateTime 对象的字段进行排序时出现错误。
查看 JQuery 代码:
$('#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>';
}
}
]
});
控制器代码:
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"]);
我的ExtensionMethod如下,基于我在网上找到的一些代码。我不完全确定我理解这段代码在做什么,这并不能帮助我找到我的问题!
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);
}
最后,尝试对包含日期的列进行排序时出现的错误:
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
这发生在扩展方法中,在线var prop = Expression.Property(param, SortField);