How to get the values of a list of inputs with the same ID by Webforms?

Asked

Viewed 847 times

2

I have a list of inputs that are automatically generated by script and they are inserted in a form thus staying:

<input type="text" id="txtValue" name="txtValue" />
<input type="text" id="txtValue" name="txtValue" />
<input type="text" id="txtValue" name="txtValue" />
...

These are not elements manipulated by the C# code-Behind (Asp.NET Wenforms application), and I need to get these values in back-end when doing the form post.

How then to capture these values?
It is possible, for example, to work with these values in the form of a vector?

Obs: When analyzing the Request.Form I found that only one txtValue element appeared.

1 answer

1


Getting values even on inputs with even Id is very simple. In this type of case Asp.net Webforms will make available the content of each element in a single string where the values will be separated by comma.

Example: 101, 104, 300 ...

To get the values then I did the following:

var values = Request.Form["txtValue"].Split(',');

The values follow the order of creation according to the nodes, and the inputs that do not receive values will come in the list as white spaces, making it easier to know which received and which received no values.

Example: 101, 300, 400 ...

Note that in this second example, after the value 101 we have two commas one after the other.
That would generate a vector like:

values[0] --> "101"
values[1] --> ""
values[2] --> "300"
values[3] --> "400"
  • Your answer is correct but it is a mistake to have more than one element with the same id, the id of an element must be unique on the page, for those cases where multiple fields with the same name must be used the attribute name of input

  • In this case it can, since it doesn’t seem to me to be used for anything, simply by changing id for name solves the problem, the Request.Form["txtValue"] should work normally, and even in tests I have done here using only the id I couldn’t get the values, only when I switched to name that worked, and I tested on IE, Chrome, Firefox and Opera 12 having the same result on all

Browser other questions tagged

You are not signed in. Login or sign up in order to post.