是否需要name属性才能从c#访问html元素? [英] Is the name attribute necessary in order to access html elements from c#?

查看:84
本文介绍了是否需要name属性才能从c#访问html元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否需要name属性才能从c#访问html元素?



IOW,为了从代码隐藏中操作网页上的值, HTML是否需要如下所示:



< input class =firstblockinputtype =textname =travelernameid =travelernametitle = 姓氏,名字,中间名字/>



...而不是:



< input class =firstblockinputtype =textid =travelernametitle =姓氏,名字,中间名/>



(例如)

Is the name attribute necessary in order to access html elements from c#?

IOW, in order to manipulate values on a web page from the code-behind, does the HTML need to look like this:

<input class="firstblockinput" type="text" name="travelername" id="travelername" title="Last Name, First Name, Middle Initial" />

...instead of this:

<input class="firstblockinput" type="text" id="travelername" title="Last Name, First Name, Middle Initial" />

(for example)

推荐答案

拥有 name 属性的唯一严重理由是使用控件一个Web表单。在这种情况下,HTTP请求由提交类型的按钮发送,并且请求数据形成为键值对的集合,因此每个控件的该属性的值被用作键,并且 - 作为值。请参阅: http://www.w3.org/TR/html401/interact /forms.html#h-17.13.3 [ ^ ]。



在服务器端,使用ASP.NET(我认为你的C#5标签表示您使用它),您可以使用 System.Web.HttpRequest 类通过其表单中的索引属性this读取值请求[密钥] https://msdn.microsoft.com/en-us/library/system.web.httprequest%28v=vs.110%29.aspx [ ^ ],

https://msdn.microsoft。 COM / EN-US /库/ xc67sd5e%28V = vs.110%29.aspx [ ^ ]。



如果您不使用表单发送HTTP请求,您可以使用Ajax,然后您不必使用此属性,因为您可以明确地提交任何可以想到的数据,包括从页面上任何控件读取的数据。然后你甚至不必拥有 id 属性,因为你可以使用JavaScript直接遍历页面的DOM树并收集你想要的数据。您可以在任何JavaScript参考中找到JavaScript DOM函数。



-SA
The only serious reason to have the name attribute is to use the control in a Web form. In this case, the HTTP request is sent by the button of the "submit" type, and the request data is formed as the set of key-value pairs, so the value of this attribute for each control is used as a key, and the value — as a value. Please see: http://www.w3.org/TR/html401/interact/forms.html#h-17.13.3[^].

On the server side, with ASP.NET (I think your "C#5" tag indicates that you use it), you can use System.Web.HttpRequest class to read the values through its indexed property "this" in the form Request["key"]: https://msdn.microsoft.com/en-us/library/system.web.httprequest%28v=vs.110%29.aspx[^],
https://msdn.microsoft.com/en-us/library/xc67sd5e%28v=vs.110%29.aspx[^].

If you don't use a form to send HTTP request, you can use Ajax, and then you don't have to use this attribute, because you can explicitly submit any thinkable data, including the data read from any your controls on the page. Then you don't even have to have the id attribute, because you can directly traverse the page's DOM tree using JavaScript and collect the data you want. You can find JavaScript DOM function in any JavaScript reference.

—SA


这篇关于是否需要name属性才能从c#访问html元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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