gpt4 book ai didi

c# - PagedList View 模型实现

转载 作者:太空宇宙 更新时间:2023-11-03 18:37:06 25 4
gpt4 key购买 nike

我正在尝试找出在 asp.net MVC 中使用 ViewModel 实现分页列表的正确方法。

假设我有以下 PagedClientViewModel:

public class PagedClientViewModel
{
public PagedList.IPagedList<ClientViewModel> Clients { get; set; }
}

public class ClientViewModel
{
public string ClientNumber { get; set; }
public string ClientName { get; set; }
}

我的 View 将引用模型如下:

@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);
}

我不想在创建 View 模型时从数据库中迭代整个客户端记录列表 - 我是否通过包含分页列表的 View 模型使事情过于复杂?我不想使用 ViewBag!

我的 ViewModel 应该是什么样的?

最佳答案

通过使用答案的组合使这个工作得很好:

    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; }
}

关于c# - PagedList View 模型实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13799255/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com