如何设置服务器端HiddenField控件的Name属性?
我想从代码隐藏中设置 ASP.NET 的 HiddenField 控件的“名称”属性,但找不到“属性”属性。难道不是有目的的吗?如何添加属性?
谢谢
I want to set the "name" attribute for HiddenField control of ASP.NET from code behind, but I cannot find the "Attributes" property. Is it not there for a purpose? How do I add the attribute?
thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
name
属性是根据 ID 自动计算的 命名容器中隐藏字段及其祖先的属性 链。你不用自己设置。您只能通过控件的 UniqueID 来访问它。The
name
attribute is automatically computed from the ID properties of the hidden field and its ancestors in the naming container chain. You don't get to set it yourself. You can only access it through the UniqueID of the control.一个可能的解决方案是,在不了解更多代码的情况下,通过将 runat="server" 属性添加到 Html 标记来使用服务器端 Html 控件而不是 ASP.NET Web 控件:
然后,您可以动态指定 id在运行时推断名称属性的代码中:
这将产生以下输出:
A possible solution, without knowing a bit more about your code, is to use a server side Html control rather than an ASP.NET web control by adding the runat="server" attribute to the Html markup:
You can then specify the id dynamically in the code behind at runtime from which the name attribute is inferred from:
This will result in the following output:
另一种非正统的处理方法是在客户端设置 name 属性。如果您要向第三方(例如 PayPal)发布信息,这会非常有用。
jQuery EG:
Another unorthodox method to deal with it is to set the name attribute client side. This is useful if you are posting to a third party such as PayPal.
jQuery EG:
忘记 HiddenField 控件并使用 Label 来代替,给它一个名称(一个 id),使其不可见,并将文本存储到其中:
使用以下命令在 javascript 中获取隐藏字段:
Forget about the HiddenField control and use a Label instead, give it a name (an id), make it invisible, and store your text into it:
Get your hidden field in your javascript with:
我最终执行此操作的方法是在 HiddenField 上设置
ClientIDMode="Static"
,然后将 ID 设置为我想要的名称。我最终得到了丑陋的身份证,但这只是让它发挥作用所付出的很小的代价。
The way I ended up doing this was to set
ClientIDMode="Static"
on the HiddenField and then set the ID to what I want my name to be.I ended up with ugly IDs but this was a small price to pay to get this to work.