ASP.NET MVC 4 覆盖发出的 html 名称和 id [英] ASP.NET MVC 4 override emitted html name and id
问题描述
我正在尝试更改由 @Html.HiddenFor
创建的 html 输入的发出名称.
I'm trying to change the emitted name of the html input created by @Html.HiddenFor
.
我正在使用的代码:
@Html.HiddenFor(e => e.SomeProperty, new { @id = "some_property", @name = "some_property" }
现在这适用于 id
,但它不适用于名称.现在我真的不在乎 id
,我需要更改 name
,因为这是回发到目标服务器的那个.
Now this works for the id
, however it doesn't work for the name. Now I don't really care for the id
now, I need the name
to change, because that's the one that get's posted back to the target server.
有吗
- 我可以在模型中对
SomeProperty
应用的属性? - 在
Html.HiddenFor
中重写name
属性的方法?
- A property I can apply on
SomeProperty
in my model? - A way in the
Html.HiddenFor
to override thename
property?
还是我只能手工做一个简单的?
Or am I stuck to do a plain <input ...>
by hand?
推荐答案
您需要使用 Html.Hidden(或手动写出)而不是
Html.HiddenFor
You need to use the Html.Hidden (or write out the <input ...>
by hand) instead of the Html.HiddenFor
@Html.Hidden("some_property", Model.SomeProperty, new { @id = "some_property" })
强类型助手(例如,名称以For"结尾的助手,如 HiddenFor
)的目标是从提供的表达式中为您猜测输入名称.因此,如果您想拥有一个自定义"输入名称,您可以随时使用诸如 Html.Hidden
之类的常规助手,您可以在其中明确设置名称.
The goal of the strongly typed helpers (e.g the one which the name end "For" like HiddenFor
) is to guess the input name for you from the provided expression. So if you want to have a "custom" input name you can always use the regular helpers like Html.Hidden
where you can explicitly set the name.
unjuken 的答案 是错误的,因为它生成了无效 HTML.
The answer from unjuken is wrong because it generates invalid HTML.
使用该解决方案生成两个 name
属性:
Using that solution generates TWO name
attributes:
<input Name="some_property" name="SomeProperty" id="some_property" type="hidden" value="test" />
所以你将有 Name="some_property"
AND name="SomeProperty"
这是 INVALID HTML因为一个输入只能有 ONE name
属性!(尽管大多数浏览器碰巧采用第一个 Name="some_property"
并且不关心第二个......)
So you will have Name="some_property"
AND name="SomeProperty"
which is INVALID HTML because an input can only have ONE name
attribute! (although most browers happen to take the first Name="some_property"
and don't care about the second one...)
这篇关于ASP.NET MVC 4 覆盖发出的 html 名称和 id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!