【发布时间】:2016-08-03 15:40:32
【问题描述】:
我正在尝试在我的索引视图中进行分页和排序而不使用 PagedList。但是我遇到了错误 -
传入字典的模型项的类型为 System.Collections.Generic.List`1[AQB_MON.Models.DeviceLog]',但此字典需要类型为“AQB_MON.ViewModels.DeviceLogIndex”的模型项。
我创建了自己的 ViewModel 来将参数传递给 Create View。当我进入 DeviceLog Index View 时,它是针对特定 DeviceID 的,我想将此 DeviceID 传递给 Create View,但是我在使用 PagedList 时遇到了一些问题。所以我找到了一个替代方案,但是我遇到了上述错误。
我的 DeviceLogIndex ViewModel 包括 -
public class DeviceLogIndex
{
public DeviceLogIndex()
{
this.DeviceLogs = new List<DeviceLog>();
}
public int DeviceID { get; set; }
public string mytest { get; set; }
public List<DeviceLog> DeviceLogs { get; set; }
而我用于分页和排序的 PageInfo ViewModel 是 -
public class PagingInfo
{
public string SortField { get; set; }
public string SortDirection { get; set; }
public int PageSize { get; set; }
public int PageCount { get; set; }
public int CurrentPageIndex { get; set; }
}
我的观点的第一部分是 -
@model AQB_MON.ViewModels.DeviceLogIndex
@{
ViewBag.Title = "Index";
}
@{
AQB_MON.ViewModels.PagingInfo info = ViewBag.PagingInfo;
}
我认为是“信息”声明导致了问题?
我的控制器是 -
public ActionResult Index(int id)
{
var devicelogs = db.DeviceLogs
.Include(d => d.Device)
.Include(d => d.DeviceLogType)
.Include(d => d.Device.ManufacturerModel)
.Where(d => d.DeviceID == id);
{
PagingInfo info = new PagingInfo();
info.SortField = "DeviceLog";
info.SortDirection = "ascending";
info.PageSize = 15;
info.PageCount = Convert.ToInt32(Math.Ceiling((double)(db.DeviceLogs.Count()/info.PageSize)));
info.PageCount +=1;
info.CurrentPageIndex = 0;
var query = devicelogs.OrderBy(c => c.DeviceLogID).Take(info.PageSize);
ViewBag.PagingInfo = info;
List<DeviceLog> model= query.ToList();
return View(model);
}
}
[HttpPost]
public ActionResult Index(PagingInfo info, int id)
{
var devicelogs = db.DeviceLogs
.Include(d => d.Device)
.Include(d => d.DeviceLogType)
.Include(d => d.Device.ManufacturerModel)
.Where(d => d.DeviceID == id);
{
IQueryable<DeviceLog> query = null;
switch(info.SortField)
{
case "EntryDate":
query = (info.SortDirection == "ascending" ?
devicelogs.OrderBy(c => c.EntryDate) :
devicelogs.OrderByDescending(c => c.EntryDate));
break;
case "LogType":
query = (info.SortDirection == "ascending" ?
devicelogs.OrderBy(c => c.DeviceLogType) :
devicelogs.OrderByDescending(c => c.DeviceLogType));
break;
}
query = query.Skip(info.CurrentPageIndex * info.PageSize).Take(info.PageSize);
ViewBag.PagingInfo = info;
List<DeviceLog> model = query.ToList();
return View(model);
}
}
【问题讨论】:
-
除了答案之外,还考虑不要将 PagingInfo 与 viewbag 一起传递,而是让您的 ViewModel 类继承 Paging 类以获得更好的结构,但这是可选的。
-
我解决了这个问题,但是分页和排序不起作用。这会是一个问题吗?我不知道如何处理你的建议。
标签: c# asp.net-mvc