'How to grab HTML elements in aspx.cs file (checkbox) C#
Let's say I have I have something along the lines of (in my aspx file):
<input name="chk" id="cbox1" type="checkbox">
<input name="chk" id="cbox2" type="checkbox">
<input name="chk" id="cbox3" type="checkbox">
<input name="chk" id="cbox4" type="checkbox">
How would I be able to get the value of each element inside the .aspx.cs file?
Can I call something like GetElementsByName in C#?
Solution 1:[1]
No, you can't, unless you will mark this controls as runat="server"
.
This is because in ASP.NET all static html became a Literal
control with .Text
property equal to your html. In this case it will be:
<asp:Literal>
<input name="chk" id="cbox1" type="checkbox">
<input name="chk" id="cbox2" type="checkbox">
<input name="chk" id="cbox3" type="checkbox">
<input name="chk" id="cbox4" type="checkbox">
</asp:Literal>
If you will mark any of elements as runat="server"
, you can access them from .Controls
collection of the current page.
Or (as in other answer) you can use the server control (CheckBox
or CheckBoxList
) for such inputs
Solution 2:[2]
You need add the attribute runat with the value server, lie so.
<input name="chk" id="cbox4" type="checkbox" runat="server">
Then you can do this.
var val = cbox4.value;
Hope this helps.
Solution 3:[3]
Use this in the aspx file instead: <asp:CheckBox runat="server" ID="cbox1">
Then in your code behind, call cbox1.Checked
to see if it is checked.
Solution 4:[4]
You can also use this.Request.Form
. Use it like this:
this.Request.Form["ElementID"].
Solution 5:[5]
Using the runat="server"
<input name="cbox1" id="cbox1" runat="server" type="checkbox">
You can use it directly like:
cbox1.Checked
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | VMAtm |
Solution 2 | Ash Burlaczenko |
Solution 3 | VMAtm |
Solution 4 | KevinCampusano |
Solution 5 |