html.ActionLink(): 如果添加 class 属性,ViewController 将停止工作

html.ActionLink(): ViewController stops working if class Attribute is added

我今天在我的项目中遇到了一个非常奇怪的行为。 所以我正在一个网站上工作,该网站具有管理员视图和普通用户视图。这些页面存储在文件夹 "Views"

下名为 "Admin" 的文件夹和名为 "User" 的文件夹中

我一开始只是为管理页面设置功能,所以我从来没有意识到我的 UserController 不起作用。它总是将我路由到 Admin/Somepage 而不是 User/Somepage.

经过一些测试,我发现了以下问题:

如果我使用

@Html.ActionLink("Admin", "AdminHome", "Admin")
@Html.ActionLink("User", "UserHome", "User")

一切正常。

但是一旦我将 class 添加到 link 例如

@Html.ActionLink("User", "UserHome", "User", new { class= "someClass" })

它停止工作了。当我现在点击 Link 到用户主页时,它会路由到 Admin/UserHome 而不是 User/UserHome显然找不到该页面。

这是为什么?有人经历过这个吗?

我的意思是我仍然可以将它包装在另一个 div 中并在那里添加 class。我只想知道这种行为背后是否有原因。

因为正如 Stephen Muecke 在他的评论中指出的那样,您应该使用的方法是 ActionLink(HtmlHelper, String, String, String, Object, Object) 并具有以下签名:

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    string controllerName,
    object routeValues,
    object htmlAttributes
)

@Html.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributes)

您当前使用的 ActionLink(HtmlHelper, String, String, Object, Object) 具有以下签名:

public static MvcHtmlString ActionLink(
    this HtmlHelper htmlHelper,
    string linkText,
    string actionName,
    object routeValues, // here you passed controllerName ("User") instead
    object htmlAttributes
)

@Html.ActionLink(linkText, actionName, routeValues, htmlAttributes)

您使用了错误的重载。通过使用这个:

@Html.ActionLink("User", "UserHome", "User", new { class= "someClass" })

ASP.Net MVC 认为the fourth parameter is route values 而不是这样。

要使其按预期工作,您需要使用 this overload that takes five parameters 并在第五个位置设置属性,如下所示:

@Html.ActionLink("User", "UserHome", "User", null, new { class= "someClass" })

我在第四个参数设置了null,因为看起来你的控制器操作不需要任何路由值。