4
客户是List<string>
。如何将数组发送到asp.net mvc中的另一个控制器方法?
RedirectToAction("ListCustomers", new { customers = customers });
当我把它包含4个项目的列表,但是当我收到它在我的控制方法,它只有一个项目,它的类型泛型列表中。这似乎不是我想要的。但是如何在控制器方法之间传递比字符串和整数更复杂的数据呢?
客户是List<string>
。如何将数组发送到asp.net mvc中的另一个控制器方法?
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>;
...
}