我现在在ASP MVC中实现数据表。我设法使其运行和搜索。但是,我想知道是否有更好的排序/排序方式? 目前,我必须手动定义列和字典的顺序,然后搜索键,然后使用值。
数据表是否具有执行此操作的本机方法?我曾经将数据表用于Codeigniter,而不必这样做。这是我的控制器和视图。
查看:
<script>
$(document).ready(function () {
$("#table").DataTable({
"ajax": {
"url": "/Users/LoadUsers",
"type": "POST",
"data": function (d) {
},
"datatype": "json"
},
"ordering": true,
"columns": [
{ "data": "Id", "name": "Id","orderable":false },
{ "data": "Email", "name": "Email" },
{ "data": "UserName", "name": "UserName" },
{ "data": "PhoneNumber", "name": "PhoneNumber" },
],
"processing":true,
"serverSide": true,
});
});
</script>
控制器:
[HttpPost]
public JsonResult LoadUsers()
{
JsonResult result = new JsonResult();
try
{
string search = Request.Form.GetValues("search[value]")[0];
string draw = Request.Form.GetValues("draw")[0];
string order = Request.Form.GetValues("order[0][column]")[0];
string orderDir = Request.Form.GetValues("order[0][dir]")[0];
int startRec = Convert.ToInt32(Request.Form.GetValues("start")[0]);
int pageSize = Convert.ToInt32(Request.Form.GetValues("length")[0]);
var data = dbContext.Users.ToList();
int totalRecords = data.Count;
var modelStructure = new Dictionary<int, string>();
modelStructure.Add(0, "Id");
modelStructure.Add(1, "Email");
modelStructure.Add(2, "UserName");
modelStructure.Add(3, "PhoneNumber");
if (!string.IsNullOrEmpty(search) && !string.IsNullOrWhiteSpace(search))
{
data = data.Where(
u => u.UserName.ToString().ToLower().Contains(search.ToLower()) ||
u.Email.ToLower().Contains(search.ToLower())
).ToList();
}
if (!(string.IsNullOrEmpty(order) && string.IsNullOrEmpty(orderDir)))
{
var columnName = modelStructure.FirstOrDefault(f => f.Key == Convert.ToInt32(order));
data = data.OrderBy(columnName.Value + " " + orderDir).ToList();
}
int recFilter = data.Count;
data = data.Skip(startRec).Take(pageSize).ToList();
var modifiedData = data.Select(u => new UsersViewModel
{
Id = u.Id,
Email = u.Email,
UserName = u.UserName,
PhoneNumber = u.PhoneNumber
});
result = this.Json(new
{
draw = Convert.ToInt32(draw),
recordsTotal = totalRecords,
recordsFiltered = recFilter,
data = modifiedData,
order = Request.Form.GetValues("order[0][column]"),
orderdir = Request.Form.GetValues("order[0][dir]")[0]
}, JsonRequestBehavior.AllowGet);
}
catch (Exception e)
{
Console.Write(e);
}
return result;
}