如何将数组发送到 asp.net mvc 中的另一个控制器方法

本文关键字:mvc 另一个 方法 控制器 net asp 数组 | 更新日期: 2023-09-27 18:35:31

客户是一个List<string>

RedirectToAction("ListCustomers", new { customers = customers }); 
当我发送列表时,它

包含 4 个项目,但是当我在我的控制器方法中收到它时,它只有一个项目,并且它是通用列表类型。这似乎不是我想要的。但是如何在控制器方法之间传递比字符串和整数更复杂的数据呢?

如何将数组发送到 asp.net mvc 中的另一个控制器方法

重定向时无法发送复杂对象。重定向时,您正在向目标操作发送 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>;
    ...
}