简体   繁体   中英

ASP.NET MVC Html.ActionLink with a List<string> parameter

How can I pass a list of parameters to a ActionLink all of which have the same name? I am using the default route.

I am looking for something like the following, but I know that anonymous objects can't have keys with the same name. Also, RoutingValueDictionary cannot have keys with the same name.

 @Html.ActionLink("Link Name", "Index", "Home", new {key="val1", key="val2", ... }, null)

Which would link to

localhost:8080/Home/Index?key=val1&key=val2& ...

How can I create this link?

You will need to create the <a> tag manually

<a href="@Url.Action("Index", "Home")?key=val1&key=val2&key=val3">Link Name</a>

however from your comments your appear to be wanting to pass the values of checkboxes, in which case you can use a form with FormMethod.Get

@using (Html.BeginForm("Index", "Home", FormMethod.Get)
{
  <input type="checkbox" name="key" value="val1" />
  <input type="checkbox" name="key" value="val2" />
  <input type="checkbox" name="key" value="val3" />
  <input type="submit" value="Save" />
}

which will generate

.../Home/Index?key=val1&key=val3

assuming you check the 1st and 3rd checkboxes

You can't pass key, key, key, key and key. Because key = key! Instead pass a list.

Create a model

public class MyModel
{
    public List<string> Keys { get; set;}
}

Accept it in your controller

public ActionResult LinkName(MyModel model)
{
    // stuff
}

And pass from your view

@using (Html.Beginform("LinkName"))
{
    <input name="Keys[0]">
    <input name="Keys[1]">
    <input type="submit" value="submit">
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM