Search code examples
asp.net-mvcasp.net-mvc-routinghtml.actionlink

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?


Solution

  • 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>