0

我有一个看起来像的控制器方法

public ViewResult Index(string id, string participant="", string flagged = "")

id是我 global.asax 中此控制器的路由值。我想将其他值作为常规参数传递,所以链接看起来像

.../controller/Index/id?participant=yes&flagged=no

有没有办法在 MVC 3 中使用 Razor 脚本生成这样的链接?

4

2 回答 2

7

routeValues您可以在 ActionLink 方法的参数中传递所有参数:

@Html.ActionLink(
    "go to index",                  // linkText
    "index",                        // actionName
    new {                           // routeValues
        id = "123", 
        participant = "yes", 
        flagged = "no" 
    }
)

假设默认路由设置,这将生成:

<a href="/Home/index/123?participant=yes&amp;flagged=yes">go to index</a>

更新:

为了进一步详细说明您发布的评论,如果 ActionLink 生成了一个 url,Length=6例如这意味着您使用了错误的重载。例如这是错误的:

@Html.ActionLink(
    "go to index",             // linkText
    "index",                   // actionName
    "home",                    // routeValues
    new {                      // htmlAttributes
        id = "123", 
        participant = "yes", 
        flagged = "no" 
    }
)

从我对每个参数名称的注释中可以看出为什么这是错误的。因此,请确保您仔细阅读 Intellisense(如果您有幸让 Intellisense 在 Razor 中工作 :-))来选择正确的辅助方法重载。

在您要指定控制器名称的情况下,正确的重载如下:

@Html.ActionLink(
    "go to index",             // linkText
    "index",                   // actionName
    "home",                    // controllerName
    new {                      // routeValues
        id = "123", 
        participant = "yes", 
        flagged = "no" 
    },
    null                       // htmlAttributes
)

注意null作为最后一个参数传递的那个。这就是htmlAttributes参数对应的内容。

于 2012-05-02T13:47:15.230 回答
3

您可以为此使用 ActionLink:

@Html.ActionLink("Title",
                 "ActionName", 
                  new {id = 1, participant = "yes", flagged = "no"})
于 2012-05-02T13:47:13.157 回答