我想在 ASP.NET MVC 应用程序上创建一个通用的服务器端 DataTable 解决方案。我在每个Index
视图上都有一个 JQuery 数据表,它带有对控制器的 AJAX 调用以检索分页数据结果。执行的操作如下:
public JsonResult GetNewRequests([ModelBinder(typeof(DataTablesModelBinder))] DataTablesPageRequest pageRequest)
{
var page = RequestsQuery(pageRequest); // Retrieves page of result from db and does any filtering + sorting
var pageResponse = DataTablesFormat.PageResponse(pageRequest, page); // Formats response for jQuery DataTable to use
return Json(pageResponse, JsonRequestBehavior.AllowGet); // Returns result
}
返回给 jQuery DataTable 控件的响应格式如下:
return new
{
sEcho = pageRequest.Echo,
iTotalRecords = report.TotalItems,
iTotalDisplayRecords = report.TotalItems,
sColumns = pageRequest.ColumnNames,
aaData = results
};
我正在处理的部分是制定要返回的模型项目列表,即:
aaData = results
results
应该是任何模型对象的列表,包括其所有相关属性。我一直在尝试reflection
与完成此解决方案一起使用ExpandoObject
,但无法弄清楚机制:
public static object PageResponse(DataTablesPageRequest pageRequest, Page<object> report)
{
List<object> results = new List<object>();
foreach(var item in report.Items)
{
dynamic dynamicObject = new ExpandoObject();
Type type = item.GetType();
PropertyInfo[] properties = type.GetProperties();
foreach(PropertyInfo property in properties)
{
Type propertyType = property.PropertyType;
// Here is where I want to add a property with the correct name of the required type to the dynamic object
dynamicObject[property.Name] = property.GetValue(item, null) as propertyType;
}
results.Add(dynamicObject);
}
return new
{
sEcho = pageRequest.Echo,
iTotalRecords = report.TotalItems,
iTotalDisplayRecords = report.TotalItems,
sColumns = pageRequest.ColumnNames,
aaData = results
};
}
即使在键入此内容时,我也已经弄清楚了一些事情。我无法弄清楚的部分:
dynamicObject[property.Name] = property.GetValue(item, null) as propertyType;
即设置属性类型 eg: DateTime
.
让我重复一遍。我想构建一个模型项目列表。这可以是具有任意数量属性的任何模型类型,每个属性可以是任何类型(int、string、bool、DateTime 等)