Click here to Skip to main content
15,884,353 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
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)
Posted

1 solution

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
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900