我正在尝试将 Telerik MVC Grid 用于需要大量过滤和分组的应用程序...在我拥有的每个模型上,它都有一个用于存储
DateTime
的 CreationDate
属性。有时,当向用户显示网格时,时间并不重要。另外,我必须使用 ViewModel 来避免循环引用,因为我使用的是 LINQ。
按日期对结果进行排序或分组时就会出现问题。如果我在 ViewModel 上使用
CreationDate
字段作为 DateTime
,然后在视图上给它一个 Format
以仅显示日期,它排序很好,工作正常,但是在使用整个日期时间值对其进行分组时,所以永远不会有任何东西被分组。如果我在 ViewModel 中使用 CreationDate
作为字符串,它第一次显示正常,但如果按日期重新排序或分组,则会出现错误。
这是我针对此案例的代码:
视图模型:
public class CenterViewModel
{
public int Id { get; set; }
public string Name{ get; set; }
public string CityName { get; set; }
public string Phone{ get; set; }
public string CreationDate { get; set; }
public bool Active { get; set; }
}
控制器:
[GridAction]
public ActionResult AjaxIndex()
{
var model = repository.GetAllRecords()
.Select(o => new CenterViewModel
{
Id = o.Id,
Name = o.Name,
CityName = o.City.Name,
Phone = o.Phone,
CreationDate = o.CreationDate.ToShortDateString(),
Active = o.Active
});
return View(new GridModel
{
Data = model
});
}
public ActionResult Index()
{
return View();
}
查看:
@model IEnumerable<CenterViewModel>
@(Html.Telerik().Grid<CenterViewModel>()
.Name("Grid")
.DataKeys(keys =>
{
keys.Add(p => p.Id);
})
.Columns(columns =>
{
columns.Bound(o => o.Name);
columns.Bound(o => o.CityName);
columns.Bound(o => o.Phone);
columns.Bound(o => o.CreationDate).Width(200);
columns.Bound(o => o.Active).Width(100)
})
.DataBinding(dataBinding =>
{
dataBinding.Ajax().Select("AjaxIndex", "Centers", null);
})
.Pageable()
.Sortable()
.Groupable()
.Filterable()
)
上面的代码仅适用于第一次加载数据,当您按日期重新排序或分组时,它将抛出以下异常:“方法‘System.String ToShortDateString()’不支持对 SQL 的转换。”这是有道理的,但是,我想我的意图现在已经很明确了。
有谁知道如何解决这个问题吗?预先感谢,
您可以尝试的一件事是在模型中使用删除时间元素的日期。然后在视图中设置日期格式。
查看模型:
public DateTime CreationDate { get; set; }
控制器:
var model = repository.GetAllRecords()
.Select(o => new CenterViewModel
{
Id = o.Id,
Name = o.Name,
CityName= o.City.Name,
Phone = o.Phone,
CreationDate = new DateTime(o.CreationDate.Year, o.CreationDate.Month, o.CreationDate.Day),
Active = o.Active
});
查看:
columns.Bound(o => o.CreationDate).Width(200).Format("{0:MM/dd/yyyy}");