我正在尝试找出在asp.net MVC中使用ViewModel实现pagedlist的正确方法。
说我有以下PagedClientViewModel:
public class PagedClientViewModel
{
public PagedList.IPagedList<ClientViewModel> Clients { get; set; }
}
public class ClientViewModel
{
public string ClientNumber { get; set; }
public string ClientName { get; set; }
}
我的观点将参考模型如下:
@model PagedClientViewModel
并且action方法如下所示:
public ActionResult Index(int? page)
{
var pageNumber = page ?? 1;
var clients = GetAllClients();
var onePageOfClients = clients.ToPagedList(pageNumber, 25);
PagedClientViewModel model = new PagedClientViewModel();
var clientViewModels = new List<ClientViewModel>();
foreach (var client in clients)
{
ClientViewModel clientVM = new ClientViewModel
{
ClientName = client.CLIENTNAME,
ClientNumber = client.CLIENTNO,
};
clientViewModels.Add(clientVM);
}
model.Clients = //how do I add the clientViewModels to the PagedList<ClientViewModel>?
return View(model);
}
我不想在创建视图模型时从数据库中迭代整个客户端记录列表 - 我是否通过拥有包含页面列表的视图模型来使事情过于复杂?我不想使用ViewBag!
我的ViewModel应该是什么样的?
答案 0 :(得分:3)
通过结合使用答案,可以很好地完成这项工作:
public ActionResult Index(PagedClientViewModel model)
{
var pageIndex = model.Page ?? 1;
var clients = from client in GetAllClients() orderby client.CLIENTNUMBER
select new ClientViewModel
{
ClientName = client.CLIENTNAME,
ClientNumber = client.CLIENTNO
};
model.Clients = clients.ToPagedList(pageIndex, 25);
return View(model);
}
public class PagedClientViewModel
{
public int? Page { get; set; }
public PagedList.IPagedList<ClientViewModel> Clients { get; set; }
}
public class ClientViewModel
{
public string ClientNumber { get; set; }
public string ClientName { get; set; }
}
答案 1 :(得分:2)
您应该更改调用以检索数据以包含页面参数并在数据库中执行过滤。这样,您只需从数据库中返回所需的数据。
var clients = GetClients(page);
此外,如果您不想循环返回的客户端(您似乎不需要这样),只需将返回的列表直接设置为ViewModel即可。像这样的东西会起作用。确保更新ViewModel,以便正确键入model.Clients
。
var clients = GetClients(page);
model.Clients = clients;
答案 2 :(得分:2)
我会简化它,就像这样:
public IEnumerable<ClientViewModel> Clients { get; set; }
和
model.Clients = from client in GetAllClients().Skip(pageNumber * PageSize).Take(PageSize)
select new ClientViewModel
{
ClientName = client.CLIENTNAME,
ClientNumber = client.CLIENTNO,
};