我很困惑为什么这个代码
Html.ActionLink("About", "About", "Home", new { hidefocus = "hidefocus" })
此链接的结果:
<a hidefocus="hidefocus" href="/Home/About?Length=4">About</a>
隐焦部分是我的目标,但?Length=4从何而来?
我很困惑为什么这个代码
Html.ActionLink("About", "About", "Home", new { hidefocus = "hidefocus" })
此链接的结果:
<a hidefocus="hidefocus" href="/Home/About?Length=4">About</a>
隐焦部分是我的目标,但?Length=4从何而来?
当前回答
Length=4来自于试图序列化一个字符串对象。你的代码正在运行这个ActionLink方法:
public static string ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes)
它接受一个字符串对象“Home”作为routeValues, MVC管道会搜索公共属性,将它们转换为路由值。在字符串对象的情况下,唯一的公共属性是Length,由于没有使用Length参数定义的路由,它将属性名和值作为查询字符串参数添加。你可能会发现,如果你从一个不是在HomeController上运行这个页面,它会抛出一个关于缺少about操作方法的错误。试着使用以下方法:
Html.ActionLink("About", "About", new { controller = "Home" }, new { hidefocus = "hidefocus" })
其他回答
也许其他人也有同样的问题,需要通过HTMLAttributes parm提供一个类值。 以下是我的解决方案:
@Html。ActionLink("About", "About", new {controller = "Home", area = ""}, new {hidefocus = "hidefocus", @class = "nav-item nav-link"})
搜索我的问题的答案落在这里,基本上是选择正确的重载@Html。ActionLink 这很重要。 我选择了一个不存在的重载(没有最后一个null), MVC没有这样的重载,导致一个错误的URL,类似于OP提到的东西。
个人提示:您可以使用匿名类型并不意味着您可以使用任何重载—这些重载是不存在的?-确定:它必须被定义! -在MVC 5.2时代来到这里
正如乔纳森·沃特尼在评论中指出的那样,这也适用于
Html BeginForm()。
方法。在我的情况下,我是在一个创造。cshtml针对对应控制器的post请求+ Create动作和had
using (Html.BeginForm("Create")) {
@Html.AntiForgeryToken()
...
}
哪个是添加查询字符串?当渲染时,Length=6"到表单动作。rroryf的认可答案暗示,并意识到“Create”的字符串长度是6,我最终通过删除显式操作规范来解决这个问题:
using (Html.BeginForm()) {
@Html.AntiForgeryToken()
...
}
请使用五(5)个参数的正确重载方法。例子:
@using (@Ajax.BeginForm("Register", "Account", null,
new AjaxOptions
{
HttpMethod = "POST",
OnSuccess = "OnSuccess",
OnFailure = "OnFailure",
OnBegin = "OnBegin",
OnComplete = "OnComplete"
}, new { @class = "form-login" }))
Html.ActionLink("About", "About", "Home", new { hidefocus = "hidefocus" }, new { })
这将承担过载: 字符串linkText,字符串actionName,字符串controllerName,对象路由值,对象htmlAttributes