asp.net-mvc 带有多个参数的 ActionLink

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5593759/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:06:20  来源:igfitidea点击:

ActionLink with multiple parameters

asp.net-mvcactionlink

提问by Cameron

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

我想创建一个像/?name=Macbeth&year=2011ActionLink这样尝试过的 URL :

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

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

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

回答by Mikael ?stberg

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

您使用的重载使year值最终出现在链接的 html 属性中(检查您的渲染源)。

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 RouteValuesdictionary like this:

您需要将两个路由值都放入RouteValues字典中,如下所示:

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

回答by hidden

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

除了 Mikael ?stberg 答案之外,在您的 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(); 
}

回答by Jansen

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

基于 Mikael ?stberg 的回答,以防万一人们需要知道它如何处理 html attr。这是另一个例子,参考来自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" } })