为什么Html.ActionLink呈现"?Length = 4"

My *_*Ego 299 asp.net-mvc

我非常困惑为什么这个代码

Html.ActionLink("About", "About", "Home", new { hidefocus = "hidefocus" })
Run Code Online (Sandbox Code Playgroud)

结果在这个链接:

<a hidefocus="hidefocus" href="/Home/About?Length=4">About</a>
Run Code Online (Sandbox Code Playgroud)

hidefocus部分是我的目标,但它?Length=4来自哪里?

ror*_*ryf 317

Length = 4来自尝试序列化字符串对象.您的代码正在运行此ActionLink方法:

public static string ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName, object routeValues, object htmlAttributes)
Run Code Online (Sandbox Code Playgroud)

string为routeValues 采用了一个对象"Home",MVC管道搜索公共属性将它们转换为路由值.在string对象的情况下,唯一的公共属性是Length,并且由于没有使用Length参数定义的路由,因此它将属性名称和值附加为查询字符串参数.您可能会发现,如果您从不在HomeController其上的页面运行此操作,则会抛出有关缺少About操作方法的错误.尝试使用以下内容:

Html.ActionLink("About", "About", new { controller = "Home" }, new { hidefocus = "hidefocus" })
Run Code Online (Sandbox Code Playgroud)

  • 为了避免这种情况,你总是可以指定你传递的参数,比如:`Html.ActionLink("About", "About", "Home", routeValues: null, htmlAttributes: new { hidefocus = "hidefocus" } )` (2认同)

Man*_*tro 188

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

Html.ActionLink("About", "About", "Home", null, new { hidefocus = "hidefocus" })
Run Code Online (Sandbox Code Playgroud)

  • 这是最好的答案..应该标记为答案. (14认同)

小智 88

您忘了添加HTMLAttributes parm.

这将无需任何更改:

Html.ActionLink("About", "About", "Home", new { hidefocus = "hidefocus" },null)
Run Code Online (Sandbox Code Playgroud)


小智 27

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

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

编辑:只是重新阅读帖子,并意识到你可能想要指定null作为倒数第二个参数,而不是最后一个.

  • 恕我直言这是SOOOO吓坏了.发生在我身上一天10次. (8认同)

use*_*436 5

Html.ActionLink("About", "About", "Home", new { hidefocus = "hidefocus" }, new { })
Run Code Online (Sandbox Code Playgroud)

这将占用重载:string linkText,string actionName,string controllerName,Object routeValues,Object htmlAttributes