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?

rtruszk
  • 3,902
  • 13
  • 36
  • 53
Cameron
  • 27,963
  • 100
  • 281
  • 483
  • Best asnwer is here https://stackoverflow.com/questions/13225786/passing-multiple-parameters-from-url-to-html-actionlink – NoWar Nov 01 '18 at 02:30

3 Answers3

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
)
Mikael Östberg
  • 16,982
  • 6
  • 61
  • 79
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(); 
}
Anthony Mastrean
  • 21,850
  • 21
  • 110
  • 188
hidden
  • 3,216
  • 8
  • 47
  • 69
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" } })
Community
  • 1
  • 1
Jansen
  • 139
  • 1
  • 3