带有多个参数的ActionLink

30
我想创建一个URL,像这样 /?name=Macbeth&year=2011 ,我尝试使用ActionLink实现,代码如下:
<%= Html.ActionLink("View Details", "Details", "Performances", new { name = item.show }, new { year = item.year })%>

但它不起作用。我该怎么办?


最佳答案在这里 https://dev59.com/NmrWa4cB1Zd3GeqP_HOE - NoWar
3个回答

65

你使用的重载使得 year 值最终出现在链接的HTML属性中(检查你渲染后的源代码)。

该重载签名如下:

MvcHtmlString HtmlHelper.ActionLink(
    string linkText, 
    string actionName, 
    string controllerName, 
    object routeValues, 
    object htmlAttributes
)
你需要将两个路由参数放入RouteValues字典中,像这样:
Html.ActionLink(
    "View Details", 
    "Details", 
    "Performances", 
    new { name = item.show, year = item.year }, 
    null
)

4
如何生成类似于“/Macbeth/2011”这样的路径? - bjan

6
除了Mikael Östberg的回答之外,您还需要在global.asax中添加以下内容:
routes.MapRoute(
    "View Details",
    "Performances/Details/{name}/{year}",
    new {
        controller ="Performances",
        action="Details", 
        name=UrlParameter.Optional,
        year=UrlParameter.Optional
    });

然后在你的控制器中

// the name of the parameter must match the global.asax route    
public action result Details(string name, int year)
{
    return View(); 
}

2

参考 Mikael Östberg 的回答,如果需要了解它如何处理 HTML 属性,请看下面的另一个例子,引用自 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" } })

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接