具有多个参数的ActionLink

Cam*_*ron 30 asp.net-mvc actionlink

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

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

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

Mik*_*erg 63

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

重载签名如下所示:

MvcHtmlString HtmlHelper.ActionLink(
    string linkText, 
    string actionName, 
    string controllerName, 
    object routeValues, 
    object htmlAttributes
)
Run Code Online (Sandbox Code Playgroud)

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

Html.ActionLink(
    "View Details", 
    "Details", 
    "Performances", 
    new { name = item.show, year = item.year }, 
    null
)
Run Code Online (Sandbox Code Playgroud)

  • 以及如何生成像`/ Macbeth/2011`这样的路径? (4认同)

hid*_*den 6

除了MikaelÖstberg之外,在你的global.asax中添加类似的东西

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

然后在你的控制器

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