簡體   English   中英

如何識別Page_Load中的回發事件

[英]How to Identify Postback event in Page_Load

我們有一些舊代碼,需要在Page_Load中標識導致回發的事件。 目前,這是通過像這樣檢查請求數據來實現的...

如果(Request.Form [“ __ EVENTTARGET”]!= null
&&(Request.Form [“ __ EVENTTARGET”]。IndexOf(“ BaseGrid”)> -1 // BaseGrid事件(例如sort)
|| Request.Form [“ btnSave”]!= null //保存按鈕

這很丑陋,如果有人重命名控件,它就會中斷。 有更好的方法嗎?

重寫每個頁面,以便現在無需在Page_Load中進行檢查。

這應該使您獲得導致回發的控件:

public static Control GetPostBackControl(Page page)
{
    Control control = null;

    string ctrlname = page.Request.Params.Get("__EVENTTARGET");
    if (ctrlname != null && ctrlname != string.Empty)
    {
        control = page.FindControl(ctrlname);
    }
    else
    {
        foreach (string ctl in page.Request.Form)
        {
            Control c = page.FindControl(ctl);
            if (c is System.Web.UI.WebControls.Button)
            {
                control = c;
                break;
            }
        }
    }
    return control;
}

在此頁面上了解有關此內容的更多信息: http : //ryanfarley.com/blog/archive/2005/03/11/1886.aspx

除了以上代碼外,如果控件的類型為ImageButton,則添加以下代碼,

if (control == null) 
{ for (int i = 0; i < page.Request.Form.Count; i++) 
    { 
        if ((page.Request.Form.Keys[i].EndsWith(".x")) || (page.Request.Form.Keys[i].EndsWith(".y"))) 
             { control = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length - 2)); break; 
             }
     }
 } 

我只是發布整個代碼(其中包括圖像按鈕/其他引起回發的控件檢查)。 謝謝埃斯波。

public Control GetPostBackControl(Page page)
{ 
   Control control = null; 
   string ctrlname = page.Request.Params.Get("__EVENTTARGET"); 
   if ((ctrlname != null) & ctrlname != string.Empty)
      { 
         control = page.FindControl(ctrlname); 
       }
  else 
      {
        foreach (string ctl in page.Request.Form) 
           { 
              Control c = page.FindControl(ctl); 
              if (c is System.Web.UI.WebControls.Button) 
                  { control = c; break; }
           }
       }
// handle the ImageButton postbacks 
if (control == null) 
{ for (int i = 0; i < page.Request.Form.Count; i++) 
    { 
        if ((page.Request.Form.Keys[i].EndsWith(".x")) || (page.Request.Form.Keys[i].EndsWith(".y"))) 
             { control = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length - 2)); break; 
             }
     }
 } 
return control; 
}

暫無
暫無

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

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