asp.net-mvc 我可以让 html.HiddenFor / Html.Hidden 创建一个 id 还是应该手动创建它?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4604009/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I get the html.HiddenFor / Html.Hidden create an id or should I just create it manually?
提问by Omu
I do this:
我这样做:
<%=Html.HiddenFor(o => o[i].HobbyId) %>
and it creates a hidden input but without id
(just name
, I need id
).
它创建了一个隐藏的输入,但没有id
(只是name
,我需要id
)。
Can I make it create an id
also ?
我可以让它也创建一个id
吗?
atm I do it like this:
atm 我这样做:
<%=Html.HiddenFor(o => o[i].HobbyId, new Dictionary<string, object>{{"id", " _ "+i+"__HobbyId"}}) %>
回答by Tom Clarkson
A cleaner way to do it is
一个更干净的方法是
<%=Html.HiddenFor(o => o[i].HobbyId, new {id = " _ "+i+"__HobbyId"}) %>
but aside from that your existing method is ok. If you really want a simple syntax you can create an extension method that calls HiddenFor, but that hardly seems worth it.
但除此之外,您现有的方法还可以。如果你真的想要一个简单的语法,你可以创建一个调用 HiddenFor 的扩展方法,但这似乎不太值得。
回答by Omu
I tend to do something such as:
我倾向于做一些事情,例如:
@Html.Hidden(
string.Format("{0}ObjectId", Model.BindingPrefix),
Model.ObjectId
)
Which produces this:
产生这个:
<input id="customerModel_ObjectId" name="customerModel.ObjectId" type="hidden" value="3a44d3eb-58ec-4229-9fe0-e420d9855bb7">
The id and name convention is consistent and produces stable id and name values that do not change. This works perfectly for me.
id 和 name 约定是一致的,并产生稳定的 id 和 name 值,不会改变。这对我来说非常有效。
So to convert your example to my format:
因此,要将您的示例转换为我的格式:
@Html.Hidden(
string.Format(" _ {0}__{1}", i, HobbyId),
HobbyId,
)
...that should get you what you want as well. Hopefully, I didn't inject any syntax errors while typing this out. :)
......这也应该让你得到你想要的。希望我在输入时没有注入任何语法错误。:)