为什么 Html.ActionLink 呈现“?Length=4"? [英] Why does Html.ActionLink render "?Length=4"

查看:37
本文介绍了为什么 Html.ActionLink 呈现“?Length=4"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑为什么这个代码

I'm VERY confused as to why this code

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

在此链接中的结果:

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

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

The hidefocus part is what I was aiming to achieve, but where does the ?Length=4 come from?

推荐答案

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

The Length=4 is coming from an attempt to serialize a string object. Your code is running this ActionLink method:

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

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

This takes a string object "Home" for routeValues, which the MVC plumbing searches for public properties turning them into route values. In the case of a string object, the only public property is Length, and since there will be no routes defined with a Length parameter it appends the property name and value as a query string parameter. You'll probably find if you run this from a page not on HomeController it will throw an error about a missing About action method. Try using the following:

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

这篇关于为什么 Html.ActionLink 呈现“?Length=4"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆