ActionLink with multiple parameters
Asked Answered
W

3

30

I want to create a URL like /?name=Macbeth&year=2011 with my ActionLink which I have tried doing like so:

<%= Html.ActionLink("View Details", "Details", "Performances", new { name = item.show }, new { year = item.year })%>

but it doesn't work. How do I do this?

Wadley answered 8/4, 2011 at 10:25 Comment(1)
Best asnwer is here #13226286Ine
H
65

The overload you are using makes the year value end up in the html attributes of the link (check your rendered source).

The overload signature looks like this:

MvcHtmlString HtmlHelper.ActionLink(
    string linkText, 
    string actionName, 
    string controllerName, 
    object routeValues, 
    object htmlAttributes
)

You need to put both your route values in to the RouteValues dictionary like this:

Html.ActionLink(
    "View Details", 
    "Details", 
    "Performances", 
    new { name = item.show, year = item.year }, 
    null
)
Harshman answered 8/4, 2011 at 10:29 Comment(1)
And how to generate path like /Macbeth/2011?Susquehanna
B
6

In addition to Mikael Östberg answer add something like this in your global.asax

routes.MapRoute(
    "View Details",
    "Performances/Details/{name}/{year}",
    new {
        controller ="Performances",
        action="Details", 
        name=UrlParameter.Optional,
        year=UrlParameter.Optional
    });

then in your controller

// the name of the parameter must match the global.asax route    
public action result Details(string name, int year)
{
    return View(); 
}
Bologna answered 6/1, 2012 at 16:42 Comment(0)
M
2

Based on Mikael Östberg answer and just in case people need to know how it does with html attr. Here is another example, reference from ActionLink

@Html.ActionLink("View Details", 
"Details", 
"Performances", 
  new { name = item.show, year = item.year }, 
  new {@class="ui-btn-right", data_icon="gear"})


@Html.ActionLink("View Details", 
"Details", 
"Performances", new RouteValueDictionary(new {id = 1}),new Dictionary<string, object> { { "class", "ui-btn-test" }, { "data-icon", "gear" } })
Myasthenia answered 3/5, 2015 at 13:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.