簡體   English   中英

我如何在后面的代碼中獲得網站另一頁的所有控制權

[英]How can i get all control in another page of site in code behind

我如何在后面的代碼中獲得網站另一頁中的所有控件。
例如,我在Default.aspx頁中,並且有一個ASP按鈕。 我想要當我單擊Button時獲得Dashboard.aspx中所有ASP控件的列表(如ButtonTextBoxDropDownList等),而無需打開Dashboard.aspx
瀏覽器中的頁面。

注意:
1.獲取所有控制過程必須在代碼隱藏中。
2.我不想在瀏覽器中打開Dashboard.aspx頁面。

我使用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 URL

注意:網址必須包含http://否則將不起作用

Page_Load Dashboard.aspx頁中編寫以下代碼:

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查找具有指定Type的所有控件,並將其寫入響應以在Default.aspx使用

它完全為我工作!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM