如何在代码中的另一个站点页面中获得所有控件

时间:2016-01-28 06:01:52

标签: c# asp.net

如何在代码后面的网站的另一个页面中获取所有控件 例如,我在Default.aspx页面,我有一个ASP按钮。 我想,当我点击Dashboard.aspx中所有ASP控件的Button获取列表时 (例如ButtonTextBoxDropDownList等),无需打开Dashboard.aspx
浏览器中的页面。

注意:
 1.让所有控制过程都必须在Code Behind中  2.我不想在浏览器中打开Dashboard.aspx页面。

1 个答案:

答案 0 :(得分:1)

我使用HttpWebRequest来解决此问题。

Default.aspx页面上Clicked按钮时,运行此代码:

byte[] dataArray = Encoding.UTF8.GetBytes("");

//url = "http://localhost:50036/UI/Dashboard.aspx?Action=FindControl"
HttpWebRequest httpRequest = (HttpWebRequest)WebRequest.Create(url);
httpRequest.Method = "POST";
httpRequest.ContentType = "application/x-www-form-urlencoded";

httpRequest.ContentLength = dataArray.Length;
Stream requestStream = httpRequest.GetRequestStream();
requestStream.Write(dataArray, 0, dataArray.Length);
requestStream.Flush();
requestStream.Close();

HttpWebResponse webResponse = (HttpWebResponse)httpRequest.GetResponse();

if (httpRequest.HaveResponse == true)
{
      Stream responseStream = webResponse.GetResponseStream();
      StreamReader responseReader = new System.IO.StreamReader(responseStream, Encoding.UTF8);
      String responseString = responseReader.ReadToEnd();
      /*
          In responseString string i have all control and types seperated by `semicolon`(`;`)
      */
}
else
      Console.Write("no response");

在此代码中url变量包含Dashboard.aspx

的网址

注意:网址必须包含http://,否则无法使用

Dashboard.aspx的{​​{1}}页面中输入以下代码:

Page_Load

protected void Page_Load(object sender, EventArgs e) { if (Request.QueryString["Action"] != null && Request.QueryString["Action"].ToString() == "FindControl") { HttpContext.Current.Response.Write(ControlsList(this)); HttpContext.Current.Response.End(); } } public void ControlsList(Control parent) { string ans = ""; foreach (Control c in parent.Controls) { if (c is TextBox || c is Button || c is DropDownList || c is CheckBox || c is RadioButton || c is CheckBoxList || c is RadioButtonList || c is ImageButton || c is LinkButton) { if(c.ID != null && c.ID != "") ans +=c.ID + "," + ((System.Reflection.MemberInfo)(c.GetType().UnderlyingSystemType)).Name + ";"; } ans += ControlsList(c); } return ans; } 检查Page_Load,然后找到具有递归函数Action=FindControl的指定类型的所有控件,并将其写入响应以在ControlsList中使用

它完全适合我!