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

clients are List<string> .

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

And when I send the list, it contains 4 elements, but when I receive it in my controller method, it has only one element and its type of the general list. This does not seem to be what I want. But how to transfer more complex data than strings and an integer between controller methods?

+4
source share
1 answer

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

Thus, one way is to save the instance somewhere on the server before redirection (for example, in the database), and then pass only the identifier as a parameter of the query string to the target action, which can retrieve the object from where it was saved :

 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 if there is a limit to the length of the query string, which will vary between 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) { ... } 

Another possibility is to use TempData (not recommended):

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

and then:

 public ActionResult ListCustomers() { TempData["customers"] as IEnumerable<string>; ... } 
+8
source

Source: https://habr.com/ru/post/1414834/


All Articles