2012-12-10 132 views
1

我想弄清楚在asp.net MVC中用ViewModel實現pagedlist的正確方法。PagedList 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; }  
} 

我的觀點將參考模型如下:

@model PagedClientViewModel 

和操作方法看起來是這樣的:

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

我不想在創建th時從數據庫迭代整個客戶端記錄列表e viewmodels - 我通過一個包含pagedlist的視圖模型來過度複雜化事物嗎?我不想使用ViewBag!

我的ViewModel應該是什麼樣子?

回答

2

您應該更改呼叫以檢索數據以包含頁面參數並在數據庫上執行過濾。這樣你只能從數據庫中返回你需要的數據。

var clients = GetClients(page); 

另外,如果你不想遍歷您返回客戶端(這似乎並不像你需要在這裏),只需直接設置返回列表視圖模型的。像這樣的東西會奏效。確保你更新你的ViewModel,這樣model.Clients就可以正確輸入了。

var clients = GetClients(page); 

model.Clients = clients; 
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, 
         }; 
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; }  
}