2012-08-02 80 views
1

我比較新使用MVC模式,這是我的第一個SO問題;我特別使用ASP.NET MVC 3,但我的問題可能適用於一般的MVC模式。重用基本上返回相同View的控制器方法的最佳方法是什麼,但可能會從數據庫中查詢不同的結果集?例如,我可能想要向所有客戶或特定地區的某些客戶或具有「精英」身份的某些客戶展示。MVC模式,控制器方法和「GetBy ...」

我目前對這些「GetBy ...」結果集中的每一個都有單獨的控制器方法。有沒有辦法使用「List」控制器並用不同的結果集填充它?也許通過注入結果集作爲參數?

回答

2

將這些方法保留在服務層中並根據輸入要求調用它。檢查傳遞給操作方法的參數。

public ActionResult List(string regionName,string status) 
{ 
    List<Customer> customerList=new List<Customer>(); 
    if((!String.IsNullOrEmpty(regionName)) && (!String.IsNullOrEmpty(status))) 
    { 
     customerList=CustomerService.GetCustomersForRegionStatus(regionName,status); 
    //List all Customers 
    } 
    else if(!String.IsNullOrEmpty(regionName)) 
    { 
    customerList=CustomerService.GetCustomersForRegion(regionName); 
    } 
    else if(!String.IsNullOrEmpty(status)) 
    { 
    customerList=CustomerService.GetCustomersForStatus(status); 
    } 
    else 
    { 
     customerList=CustomerService.GetAllCustomers(); 
    } 
    return View(customerList); 
} 

而且你的觀點會被限定到Customer對象的集合

@model IList<Customer> 
@foreach(var cust in Model) 
{ 
    <p>@cust.Name</p> 
} 

假設GetCustomersForRegionStatusGetCustomersForRegionGetAllCustomers方法返回Customer對象的列表,並在內部調用不同的數據庫訪問方法,以獲取根據傳遞的參數過濾數據。

這些爲urls請求會給現在不同的結果。

yourcontrollername/list 
yourcontrollername/list?regionName=someregion 
yourcontrollername/list?status=elite 
yourcontrollername/list?regionName=someregion&status=elite 
+0

謝謝你的迴應。這正是我所期待的。 – tonyapolis 2012-08-03 12:37:09