Pass List<int> from actionlink to controller method
Asked Answered
B

2

5

In my controller I have this:

ViewBag.lstIWantToSend= lstApps.Select(x => x.ID).ToList();  // creates a List<int> and is being populated correctly

I want to pass that list to another controller.. so in my view I have:

@Html.ActionLink(count, "ActionName", new { lstApps = ViewBag.lstIWantToSend }, null)

Method in Controller:

public ActionResult ActionName(List<int> lstApps)   // lstApps is always null

Is there a way to send a list of ints as a route value to a controller method?

Badajoz answered 15/3, 2017 at 17:15 Comment(2)
you cannot pass a complex type this way via Html.ActionLinkYolondayon
This is not really a list of objects, but just a list of ints. Just convert that to a csv string of ints to send it and then parse in your receiving action.Avens
M
7

its not possible directly but you can do it with Json if i have List<int>

ViewBag.lstIWantToSend= new List<int> {1, 2, 3, 4};

so my view would be something like

@Html.ActionLink(count, "ActionName", new { lstApps = Json.Encode(ViewBag.lstIWantToSend) }, null)

Json.Encode will convert List<int> to json string

and ActionName will be like this

 public ActionResult ActionName (string lstApps)
        {
            List<int> result = System.Web.Helpers.Json.Decode<List<int>>(lstApps);

            return View();

        }

Json.Decode<List<int>> will convert this json string back to List<int>

Mcburney answered 15/3, 2017 at 18:45 Comment(2)
Awesome! I don't know much at all about json, but that did it. If you don't mind me asking, how did you figure out to do it that way?Badajoz
json is mostly used for sending objects in web api so you can do the same thing here because html does not encode List<int> but it does recognize any string so thats why json converts objects to stringMcburney
L
0

MVC.net works on the convention that everything you send is a single Model. So if you want to send a list of objects (say a List of Persons) - it might be a good idea to serialize them first both from client to server, and from server to client.

On simple things, like @BryanLewis said, you can simply serialize it yourself with CSV (to string), and then split it back on the recieving Action/Client. For more complex things you have (client side) things like AngularJS with its excelent JSON.stringify(anyObject)/JSON.parse(anyString) and you have (server side) Newton.Soft 's excelent JsonConvert.Deserialize>(myJsonString) or JsonConvert.Serialize(someObject). The nice thing about json is that it's very transparent.

Bear in mind - HTTP does not like objects. But it's great with passing strings back and forth.

Leu answered 18/7, 2018 at 8:35 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.