为什么Html。ActionLink render "?Length=4;

我很困惑为什么这个代码

Html.ActionLink("About", "About", "Home", new { hidefocus = "hidefocus" })

此链接的结果:

<a hidefocus="hidefocus" href="/Home/About?Length=4">About</a>

hidefocus部分是我想要实现的,但是?Length=4从哪里来?

94782 次浏览

ActionLink的参数不正确,它试图使用“Home”值作为路由值,而不是匿名类型。

我相信你只需要添加new { }null作为最后一个参数。

编辑:只是重新阅读了这篇文章,并意识到您可能希望将null指定为第二个最后一个参数,而不是最后一个参数。

Length=4来自于试图序列化一个字符串对象。你的代码正在运行这个ActionLink方法:

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

这将接受一个string对象“Home”作为routeValues, MVC管道会搜索公共属性,将它们转换为路由值。在string对象的情况下,唯一的公共属性是Length,由于没有使用Length参数定义的路由,它将属性名和值作为查询字符串参数添加。你可能会发现,如果你在不是HomeController的页面上运行这个,它会抛出一个关于缺少About操作方法的错误。试着使用以下方法:

Html.ActionLink("About", "About", new { controller = "Home" }, new { hidefocus = "hidefocus" })

我解决这个问题的方法是在匿名声明(new {})之前添加一个null到第四个参数,以便它使用以下方法重载:(linkText, actionName, controllerName, routeValues, htmlAttributes):

Html.ActionLink("About", "About", "Home", null, new { hidefocus = "hidefocus" })

只需删除“Home”(控制器的名称),这样代码将是:

Html.ActionLink("About", "About", new { hidefocus = "hidefocus" })

你忘记添加HTMLAttributes parm。

这将在没有任何更改的情况下工作:

Html.ActionLink("About", "About", "Home", new { hidefocus = "hidefocus" },null)

正如乔纳森·沃特尼在评论中指出的那样,这也适用于

Html.BeginForm ()

方法。在我的例子中,我在Create.cshtml中针对对应控制器的post请求+ Create动作,并且有

using (Html.BeginForm("Create")) {
@Html.AntiForgeryToken()
...
}

它在呈现时将查询字符串”?长度= 6”添加到表单操作中。rroryf的认可答案暗示,并意识到“Create”的字符串长度是6,我最终通过删除显式操作规范来解决这个问题:

using (Html.BeginForm()) {
@Html.AntiForgeryToken()
...
}
Html.ActionLink("About", "About", "Home", new { hidefocus = "hidefocus" }, new { })

这将采取重载: string linkText, string actionName, string controllerName,对象路由值,对象htmlAttributes

属性名:

 @Html.ActionLink(linkText: "SomeText", actionName: "SomeAction", controllerName: "SomeControllerName", routeValues: new { parameterName = parameterValue}, htmlAttributes: null)

请使用五(5)个参数的正确重载方法。例子:

@using (@Ajax.BeginForm("Register", "Account", null,
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccess",
OnFailure = "OnFailure",
OnBegin = "OnBegin",
OnComplete = "OnComplete"
}, new { @class = "form-login" }))
也许其他人也有同样的问题,需要通过HTMLAttributes parm提供一个值。 这是我的解决方案:

@Html.ActionLink("About", "About", new { controller = "Home", area = "" }, new { hidefocus = "hidefocus", @class = "nav-item nav-link" })

搜索我的问题的答案落在这里,基本上它是@Html.ActionLink的正确重载的选择 enter image description here 这很重要。
我选择了一个不存在的重载(没有 the 最后的 null),而< em > MVC < / em >没有这样的重载,导致错误的URL,类似于上面提到的OP。

一个个人的< em >注意:< / em >你可以use匿名类型并不意味着你可以使用任何重载- 这做不存在?- < em >确定:< / em > 待定义!< br > -在MVC 5.2时代来到这里

这工作得很好

@Html.ActionLink("Informationen", "About", "Home", new { area = "" }, new { @class = "nav-link" })

new { area = "" }补充道。