Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send array to another controller method in asp.net mvc?

Tags:

c#

asp.net-mvc

customers is a List<string>.

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

And when I send the list it contains 4 items, but when I receive it in my controller method it has only one item and it's of type generic list. That seems not be what I want. But how to pass more complex data than strings and integer between controller methods?

like image 921
marko Avatar asked Feb 21 '23 08:02

marko


1 Answers

You cannot send complex objects when redirecting. When redirecting you are sending a GET request to the target action. When sending a GET request you need to send all information as query string parameters. And this works only with simple scalar properties.

So one way is to persist the instance somewhere on the server before redirecting (in a database for example) and then pass only an id as query string parameter to the target action which will be able to retrieve the object from where it was stored:

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

and inside the target action:

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

Another possibility is to pass all the values as query string parameters (be careful there's a limit in the length of a query string which will vary among browsers):

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)
{
    ...
}

Yet another possibility is to use TempData (not recommended):

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

and then:

public ActionResult ListCustomers()
{
     TempData["customers"] as IEnumerable<string>;
    ...
}
like image 65
Darin Dimitrov Avatar answered Mar 08 '23 09:03

Darin Dimitrov