1

我有一个网格:

 @(Html.Grid("grid")
      .SetJsonReader(new MvcJqGrid.DataReaders.JsonReader { Id = "Id", RepeatItems = false })
      .SetRequestType(RequestType.Post)
      .AddColumn(new Column("Date").SetWidth(300).SetLabel("Date").)
      .SetUrl(Url.Action("Action", "Controller"))
      .SetRowNum(10)
      .SetHeight(500)
      .SetRowList(new[] { 10, 15, 20, 50 })
      .SetViewRecords(true)
      .SetGridView(true)
      .SetPager("pager")
    )

和该网格的数据:

[HttpPost]
public JsonResult Action(GridSettings gridSettings)
{
    var data = new List<DateTime>();
    data.AddRange(Enumerable.Range(0, 1000).Select(s => new
    {
        Date = DateTime.Now.AddHours(s * 4),
    }));
    int totalRecords = data.Count;
    if (!string.IsNullOrWhiteSpace(gridSettings.SortColumn))
    {
        data = (gridSettings.SortOrder == "asc" ?
            data.AsQueryable().OrderByPropertyName(gridSettings.SortColumn) :
            data.AsQueryable().OrderByPropertyNameDescending(gridSettings.SortColumn)).ToArray();
    }
    data = data.Skip((gridSettings.PageIndex - 1) * gridSettings.PageSize).Take(gridSettings.PageSize).ToArray();

    var jsonData = new
    {
        total = totalRecords / gridSettings.PageSize + 1,
        page = gridSettings.PageIndex,
        records = totalRecords,
        rows = data
    };
    return Json(jsonData);
}

那么问题是我应该如何使用日期?如果我将它们保留为 DateTime,它们将不显示任何格式,但使用Date = DateTime.Now.AddHours(s * 4).ToString(), 将不会正确排序?

4

1 回答 1

1

您可以在排序后格式化数据(我稍微重构了您的控制器操作以使其正常工作):

[HttpPost]
        public JsonResult GetData(GridSettings gridSettings)
        {
            var data = Enumerable.Range(0, 1000).Select(s => DateTime.Now.AddHours(s * 4)).ToList();

            var totalRecords = data.Count();

            if (!string.IsNullOrWhiteSpace(gridSettings.SortColumn))
            {
                data = (gridSettings.SortOrder == "asc" ?
                    data.OrderBy(x=>x) :
                    data.OrderByDescending(x=>x)).ToList();
            }
            data = data.Skip((gridSettings.PageIndex - 1) * gridSettings.PageSize).Take(gridSettings.PageSize).ToList();

            var id = (gridSettings.PageIndex - 1) * gridSettings.PageSize;

            var jsonData = new
            {
                total = totalRecords / gridSettings.PageSize + 1,
                page = gridSettings.PageIndex,
                records = totalRecords,
                rows = data.Select(d=>new
                    {
                        id = ++id,
                        Date = d.ToShortDateString()
                    })
            };
            return Json(jsonData);
        }
于 2013-05-08T14:09:21.750 回答