使用Request.Form中的属性获取所有控件?

时间:2017-03-16 09:07:59

标签: c# asp.net postback

我希望在回发事件上获得所有输入控件。

  

这是我的样本控制:

 <input name="ctl00$ContentBody$dt_62f6f44864ec4c4892ac074da0209ff4
 type="text" value="11.06.2014"
 id="ContentBody_dt_62f6f44864ec4c4892ac074da0209ff4"  
 class="m-wrap span12 date form_datepicker form-control" 
 data-pagetype="main"
 data-groupname="group_DATE"
 data-rowindex="0" data-objtype="Datepicker"
 data-columnname="DATE_FROM" style="width:50px;">
  

处理所有密钥

public Collection<ActionContainer.RequestFormParameter> GetFormParameters()
{
   System.Collections.IEnumerator e2 = Request.Form.GetEnumerator();

   while (e2.MoveNext())
   {
       ActionContainer.RequestFormParameter params_;
       String xkey = (String)e2.Current; // output "ContentBody_dt_62f6f44864ec4c4892ac074da0209ff4"
       String xval = Request.Form.Get(xkey); // output "11.06.2014"
       String AttrCollection = ??

       // I try to find control by id but it didn't work for me
   }
}

1 个答案:

答案 0 :(得分:0)

Request.Form集合中不包含属性。因此,您必须使用FindControl来查找Control并访问它的属性。但是,由于您拥有的是控制名称(key),因此您必须具有创造性才能获得实际的ID

让我们假设您有一个ID为dt_62f6f44864ec4c4892ac074da0209ff4的TextBox。在表单帖子中,它将类似ctl00$ContentPlaceHolder1$dt_62f6f44864ec4c4892ac074da0209ff4,因此我们可以再次提取ID

使用FindControl来查找Control,使用正确的控件类型转换它的属性。

//loop all the items in the form collection
foreach (string key in Request.Form.Keys)
{
    //check if the key contains a $, in which case it is probably an aspnet control
    if (key.Contains("$"))
    {
        //split the control name
        string[] keyArrar = key.Split('$');

        //get the last part in the array, which should be the ID of the control
        string controlID = keyArrar[keyArrar.Length - 1];

        //try to find the control with findcontrol, in this case with master pages
        object control = this.Master.FindControl("mainContentPane").FindControl(controlID) as object;

        //check if the control exist and if it is a textbox
        if (control != null && control is TextBox)
        {
            //cast the object to the actual textbox
            TextBox tb = control as TextBox;

            //loop all the attributes of the textbox
            foreach (string attr in tb.Attributes.Keys)
            {
                //get the key and value of the attribute
                Response.Write(attr + ": " + tb.Attributes[attr] + "<br>");
            }
        }
    }
}

输出

data-pagetype: main
data-groupname: group_DATE
data-rowindex: 0
data-objtype: Datepicker
data-columnname: DATE_FROM

aspx页面上的演示TextBox。

<asp:TextBox ID="dt_62f6f44864ec4c4892ac074da0209ff4" runat="server"
    data-pagetype="main"
    data-groupname="group_DATE"
    data-rowindex="0"
    data-objtype="Datepicker"
    data-columnname="DATE_FROM">
</asp:TextBox>

正如你所看到的那样,它是一种非常复杂的方式......