如何在代码后面的网站的另一个页面中获取所有控件
例如,我在Default.aspx
页面,我有一个ASP按钮。
我想,当我点击Dashboard.aspx
中所有ASP控件的Button获取列表时
(例如Button
,TextBox
,DropDownList
等),无需打开Dashboard.aspx
浏览器中的页面。
注意:
1.让所有控制过程都必须在Code Behind中
2.我不想在浏览器中打开Dashboard.aspx
页面。
答案 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
中使用
它完全适合我!