我正在尝试将 Telerik MVC Grid 用于需要大量过滤和分组的应用程序...在我拥有的每个模型上,它都有一个属性 DateTime 用于存储 CreationDate。有时,当向用户显示网格时,时间并不重要。另外,我必须使用 ViewModel 来避免循环引用,因为我使用的是 LINQ。
按日期对结果进行排序或分组时会出现问题。如果我使用 CreationDate 字段作为我的 ViewModel 上的日期时间,然后在 View 上给它格式以仅显示日期,它排序很好,工作正常,但是当使用整个日期时间值对其进行分组时,因此永远不会有任何分组。如果我在 ViewModel 中使用 CreationDate 作为字符串,它第一次显示正常,但如果按日期排序或分组,则会出现错误。
这是我针对此案例的代码:
View 模型:
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; }
}
Controller :
[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 的转换。”这是有道理的,但是,我认为我的意图现在已经很明确了。
有谁知道如何解决这个问题吗?提前致谢,
最佳答案
您可以尝试的一件事是在模型中使用删除时间元素的日期。然后在 View 中设置日期格式。
View 模型:
public DateTime CreationDate { get; set; }
Controller :
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}");
关于asp.net-mvc-3 - Telerik MVC Grid - 按日期分组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9280777/