利用JS动态创建html控件并在后台实现取值
经常我们在开发中可能需要动态创建一些控件,如果动态创建web控件又很麻烦,本文介绍给你如何利用JS创建html控件并在后台取值,废话少说,上菜:
Code
1<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="GetHtmlCtrValue.aspx.cs"
2 Inherits="RoadShow.Web.GetHtmlCtrValue" %>
3
4<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
5<html xmlns="http://www.w3.org/1999/xhtml">
6<head runat="server">
7 <title>无标题页</title>
8
9 <script language="javascript" type="text/javascript">
10 function CreateInputTxt()
11 {
12 document.getElementById("Count").value++;
13 var i=0;
14 if(i<5)
15 {
16 i++;
17 div1.innerHTML=div1.innerHTML + "<input type='text' name='text"+i+"' style='width:270px;' MaxLength='20' ><br>";
18 }
19 if(i>6)
20 {
21 alert("选项不应超过6个");
22 }
23 }
24 </script>
25
26</head>
27<body>
28 <form id="form1" runat="server">
29 <div id="div1">
30 <input type="text" name="txtFile" />
31 <a href="javascript:CreateInputTxt();">添加新的text</a>
32 <asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" />
33 </div>
34 <asp:HiddenField ID="Count" runat="server" Value="0" />
35 </form>
36</body>
37</html>
后台代码:
Code
1using System;
2using System.Collections;
3using System.Configuration;
4using System.Data;
5using System.Linq;
6using System.Web;
7using System.Web.Security;
8using System.Web.UI;
9using System.Web.UI.HtmlControls;
10using System.Web.UI.WebControls;
11using System.Web.UI.WebControls.WebParts;
12using System.Xml.Linq;
13
14namespace RoadShow.Web
15{
16 public partial class GetHtmlCtrValue : System.Web.UI.Page
17 {
18 protected void Page_Load(object sender, EventArgs e)
19 {
20
21 }
22
23 protected void Button1_Click(object sender, EventArgs e)
24 {
25 //获得text的个数
26 int i = int.Parse(this.Count.Value);
27 //Response.Write(i);
28 //定义个数组,用来接受text的值
29 string[] strArray = new string[i];
30 for (int j = 0; j < i; j++)
31 {
32 strArray[j] = Request.Form["text" +(j+1)];
33
34 }
35 foreach (string str in strArray)
36 {
37 //测试strArray里有没有值
38 Response.Write(str);
39 }
40 //for (i = 1; i < 6; i++)
41 //{
42 // Response.Write(Request.Form["text" + i]);
43 //}
44 }
45 }
46}