后台取得非服务器控件的一种方法(Request.Form.GetKey(i))

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Tables.aspx.cs" Inherits="test_Tables" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    
<title>后台取得非服务器控件的一种方法(Request.Form.GetKey(i))</title>
</head>
<body>
    
<form id="form1" runat="server" onsubmit="">
    
<div>
        
<input id="chk_1" name="chk_1" type="checkbox" />
        
<input id="chk_2" name="chk_2" type="checkbox" />
        
<table>
            
<tr>
                
<td id="tdServer" runat="server">
                
                
</td>
            
</tr>
        
</table>
        
<asp:Button ID="btnShow" runat="server" Text="Show" onclick="btnShow_Click" />
    
</div>
    
</form>
</body>
</html>
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class test_Tables : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {
        
if (!IsPostBack)
            Bind();
    }
    
/// <summary>
    
/// 后台操作table
    
/// </summary>
    private void Bind()
    {
        HtmlTableCell hCell01 
= new HtmlTableCell();
        hCell01.InnerText 
= "hello01<input type=text />";//InnerText与InnerHtml的区别
        HtmlTableCell hCell02 = new HtmlTableCell();
        hCell02.InnerHtml 
= "hello02<input id=\"chk_3\" type=\"checkbox\" name=\"chk_3\" />";

        HtmlTableRow hRow1 
= new HtmlTableRow();
        hRow1.Cells.Add(hCell01);
        hRow1.Cells.Add(hCell02);

        HtmlTable hTable 
= new HtmlTable();
        hTable.Border 
= 1;
        hTable.Rows.Add(hRow1);

        tdServer.Controls.Add(hTable);
    }
    
/// <summary>
    
/// 后台取得非服务器控件checkbox的值,这里的值就是name属性
    
/// </summary>
    
/// <param name="sender"></param>
    
/// <param name="e"></param>
    protected void btnShow_Click(object sender, EventArgs e)
    {
        
string names = "";
        
for (int i = 0; i < Request.Form.Count; i++)
        {
            
string strChk = Request.Form.GetKey(i);//这里取得的是name属性,如果没有设置name属性将取不到。
            if (strChk.IndexOf("chk_"== 0)
            {
                names 
+= strChk + ",";
            }
        }
        Response.Write(names 
+ "///" + Request.Form.Count);
    }
}

原文地址:https://www.cnblogs.com/greatverve/p/1592546.html