How to grab HTML elements in aspx.cs file (checkbox) C#

孤街醉人 提交于 2019-12-23 16:05:55

问题


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#?


回答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




回答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.




回答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.




回答4:


You can also use this.Request.Form. Use it like this:

this.Request.Form["ElementID"].



回答5:


Using the runat="server"

<input name="cbox1" id="cbox1" runat="server" type="checkbox">

You can use it directly like:

cbox1.Checked



来源:https://stackoverflow.com/questions/6685176/how-to-grab-html-elements-in-aspx-cs-file-checkbox-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!