2012-05-29 42 views
4

客戶是List<string>如何將數組發送到asp.net mvc中的另一個控制器方法?

RedirectToAction("ListCustomers", new { customers = customers }); 

當我把它包含4個項目的列表,但是當我收到它在我的控制方法,它只有一個項目,它的類型泛型列表中。這似乎不是我想要的。但是如何在控制器方法之間傳遞比字符串和整數更復雜的數據呢?

回答

8

重定向時無法發送複雜對象。重定向時,您正在向目標操作發送GET請求。發送GET請求時,您需要將所有信息作爲查詢字符串參數發送。這隻適用於簡單的標量屬性。

因此,一種方法是在重定向之前在服務器上的某處持久化實例(例如在數據庫中),然後僅將id作爲查詢字符串參數傳遞給目標操作,該操作將能夠從其中檢索對象儲存:

int id = Persist(customers); 
return RedirectToAction("ListCustomers", new { id = id }); 

和目標動作內:

public ActionResult ListCustomers(int id) 
{ 
    IEnumerable<string> customers = Retrieve(id); 
    ... 
} 

另一種可能性是通過所有的值作爲查詢字符串參數(注意有在查詢字符串的長度的限制,其將不同瀏覽器之間):

public ActionResult Index() 
{ 
    IEnumerable<string> customers = new[] { "cust1", "cust2" }; 
    var values = new RouteValueDictionary(
     customers 
      .Select((customer, index) => new { customer, index }) 
      .ToDictionary(
       key => string.Format("[{0}]", key.index), 
       value => (object)value.customer 
      ) 
    ); 
    return RedirectToAction("ListCustomers", values); 
} 

public ActionResult ListCustomers(IEnumerable<string> customers) 
{ 
    ... 
} 

又一種可能性是使用TempData的(不推薦):

TempData["customer"] = customers; 
return RedirectToAction("ListCustomers"); 

然後:

public ActionResult ListCustomers() 
{ 
    TempData["customers"] as IEnumerable<string>; 
    ... 
} 
相關問題