Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass List<int> from actionlink to controller method

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?

like image 300
Grizzly Avatar asked Mar 15 '17 17:03

Grizzly


People also ask

How do I transfer data from ActionLink to controller?

ActionLink is rendered as an HTML Anchor Tag (HyperLink) and hence it produces a GET request to the Controller's Action method which cannot be used to send Model data (object). Hence in order to pass (send) Model data (object) from View to Controller using @Html.

What is HTML ActionLink ()?

Html. ActionLink creates a hyperlink on a view page and the user clicks it to navigate to a new URL. It does not link to a view directly, rather it links to a controller's action.

What is difference between HTML ActionLink and URL action?

Yes, there is a difference. Html. ActionLink generates an <a href=".."></a> tag whereas Url. Action returns only an url.


1 Answers

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>

like image 119
Usman Avatar answered Nov 15 '22 05:11

Usman