How can I use Url.Action with list parameters?

asp.net-mvc, asp.net-mvc-5, c#

Solution

Instead of using an Anonymous Type, build a `RouteValueDictionary`. Format the parameters as `parameter[index]`.

@{
    var categories = new List<int>() { 6, 7 };

    var parameters = new RouteValueDictionary();

    for (int i = 0; i < categories.Count; ++i)
    {
        parameters.Add("category[" + i + "]", categories[i]);
    }
}

Then,

@Url.Action("Test", parameters)

Problem

Say I have an action method: ``` [HttpGet] public ActionResult Search(List<int> category){ ... } ``` The way the MVC model binding works, it expects a list of category like this: ``` /search?category=1&category=2 ``` So my questions are: How do I create that link using Url.Action() if I just hardcode it? ``` Url.Action("Search", new {category=???}) //Expect: /search?category=1&category=2 ``` How do I create that link using Url.Action() if my input is a list of int? ``` var categories = new List<int>(){1,2}; //Expect: /search?category=1&category=2 Url.Action("Search", new {category=categories}) //does not work, ```

Original source