給你推薦兩種方法,一種是向服務(wù)器容器控件里添加子控件(即向runat=server的控件的Controls里添加控件),第二種是就是你的這種拼接HTML的方法不過這種方法必須設(shè)置控件的name屬性,然后在Request.Form["控件的name"]里獲得控件的值,推薦使用第一種方法,更直觀一些,第二種無法記錄提交以后的狀態(tài),代碼如下
第一種
后臺
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
using System.Web.UI.HtmlControls; protected void Page_Load( object sender, EventArgs e) { for ( int i = 0; i < 4; i++) { HtmlInputCheckBox htmlInputCheckBox = new HtmlInputCheckBox(); //這里用CheckBox也是一樣的 htmlInputCheckBox.ID = "check" + i; Container.Controls.Add(htmlInputCheckBox); } } protected void Button1_Click( object sender, EventArgs e) { for ( int i = 0; i < 4; i++) { Label1.Text += "<br/>" + (Container.FindControl( "check" + i) as HtmlInputCheckBox).Checked.ToString(); } } |
前臺
1
2
3
4
5
6
|
<form id= "form1" runat= "server" > <div id= "Container" runat= "server" > </div> <asp:Button ID= "Button1" runat= "server" Text= "Button" onclick= "Button1_Click" /> <asp:Label ID= "Label1" runat= "server" ></asp:Label> </form> |
第二種
后臺
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
public string GetCheckBox() { return "<input name=\"Checkbox1\" type=\"checkbox\"/>" ; //這里必須設(shè)置name,Id沒有用 } protected void Button1_Click( object sender, EventArgs e) { if (Request.Form[ "Checkbox1" ] == null ) //如果Checkbox1為未選中狀態(tài)Request.Form["Checkbox1"]值為null { Label1.Text += "<br/>Fasle" ; } else //如果Checkbox1為選中狀態(tài)Request.Form["Checkbox1"]值為on { Label1.Text += "<br/>True" ; } } |
前臺
1
2
3
4
5
6
7
|
<form id= "form1" runat= "server" > <div> <%=GetCheckBox() %> </div> <asp:Button ID= "Button1" runat= "server" Text= "Button" OnClick= "Button1_Click" /> <asp:Label ID= "Label1" runat= "server" ></asp:Label> </form> |