[英]How to send array to another controller method in asp.net mvc?
customers是List<string>
。
RedirectToAction("ListCustomers", new { customers = customers });
當我發送列表時,它包含4個項目,但是當我在我的控制器方法中收到它時,它只有一個項目,它的類型為通用列表。 這似乎不是我想要的。 但是如何在控制器方法之間傳遞比字符串和整數更復雜的數據?
重定向時無法發送復雜對象。 重定向時,您正在向目標操作發送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>;
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.