2011-04-18 42 views
3

我想弄明白什麼按鈕被點擊了,這段代碼在IE中工作得很好,但是如果我的Chrome,Firefox或Safari沒有做任何事情。在firefox中使用firebug時,我查看了Form Details,它表明EVENTTARGET沒有任何價值,只是空白。我怎樣才能讓它在FF,Chrome和Safari上運行?EVENTTARGET確定發件人的問題

方法:

 Control postbackControlInstance = null; 

     string postbackControlName = page.Request.Params.Get("__EVENTTARGET"); 
     if (postbackControlName != null && postbackControlName != string.Empty) 
     { 
      postbackControlInstance = page.FindControl(postbackControlName); 
     } 
     else 
     { 
      for (int i = 0; i < page.Request.Form.Keys.Count; i++) 
      { 
       postbackControlInstance = page.FindControl(page.Request.Form.Keys[i]); 
       if (postbackControlInstance is System.Web.UI.WebControls.Button) 
       { 
        return postbackControlInstance; 
       } 
      } 
     } 
     if (postbackControlInstance == 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"))) 
       { 
        postbackControlInstance = page.FindControl(page.Request.Form.Keys[i].Substring(0, page.Request.Form.Keys[i].Length - 2)); 
        return postbackControlInstance; 
       } 
      } 
     } 
     return postbackControlInstance; 

代碼中調用方法:

 if (Page.IsPostBack) 
     { 
      try 
      { 
       Control cause = GetPostBackControl(Page); 
       string statecause = cause.ID; 
       if (statecause == "buttonName1") 
       { 
        search(statecause); 
       } 
       else if (statecause == "buttonNAME2") 
       { 
        resetfields(); 
       } 
      } 
      catch { } 
     } 

回答

3

最好的方法是確定什麼原因引起控制回發是重寫protectedPage.RaisePostBackEvent方法。此方法使用ASP.NET基礎建設,以通知引起的,它應處理傳入的回發事件回發的服務器控件:

public class MyPage : Page 
{ 
    protected override void RaisePostBackEvent(
     IPostBackEventHandler sourceControl, 
     string eventArgument 
    ) 
    { 
     // here is the control that caused the postback 
     var postBackControl = sourceControl; 

     base.RaisePostBackEvent(sourceControl, eventArgument); 
    } 
} 

您提供應該scenarious工作代碼時,客戶端__doPostBack功能渲染到頁面(例如,如果您只使用一個按鈕,如<asp:Button runat="server" ID="btnSubmit" Text="submit" UseSubmitBehavior="true" />則不會渲染)。

如果即使在情況下,當__doPostBack功能呈現,但__EVENTTARGET參數爲空則意味着__doPostBack函數的默認行爲是通過自定義的/不兼容的JavaScript代碼在大多數情況下侵犯。在這種情況下,即使ASP.NET基礎結構也無法正確處理回發事件。