【问题标题】:On postback, how can I check which control cause postback in Page_Init event在回发时,如何检查哪个控件导致 Page_Init 事件中的回发
【发布时间】:2011-03-11 16:05:24
【问题描述】:

在回发时,如何在 Page_Init 事件中检查哪个控件导致回发。

protected void Page_Init(object sender, EventArgs e)
{
//need to check here which control cause postback?

}

谢谢

【问题讨论】:

    标签: c# asp.net page-lifecycle


    【解决方案1】:

    我看到已经有一些很好的建议和方法建议如何获得回发控制权。但是我发现了另一个网页 (Mahesh blog),其中包含检索回发控件 ID 的方法。

    我将在此处发布它并稍作修改,包括使其成为扩展类。希望它以这种方式更有用。

    /// <summary>
    /// Gets the ID of the post back control.
    /// 
    /// See: http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
    /// </summary>
    /// <param name = "page">The page.</param>
    /// <returns></returns>
    public static string GetPostBackControlId(this Page page)
    {
        if (!page.IsPostBack)
            return string.Empty;
    
        Control control = null;
        // first we will check the "__EVENTTARGET" because if post back made by the controls
        // which used "_doPostBack" function also available in Request.Form collection.
        string controlName = page.Request.Params["__EVENTTARGET"];
        if (!String.IsNullOrEmpty(controlName))
        {
            control = page.FindControl(controlName);
        }
        else
        {
            // if __EVENTTARGET is null, the control is a button type and we need to
            // iterate over the form collection to find it
    
            // ReSharper disable TooWideLocalVariableScope
            string controlId;
            Control foundControl;
            // ReSharper restore TooWideLocalVariableScope
    
            foreach (string ctl in page.Request.Form)
            {
                // handle ImageButton they having an additional "quasi-property" 
                // in their Id which identifies mouse x and y coordinates
                if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
                {
                    controlId = ctl.Substring(0, ctl.Length - 2);
                    foundControl = page.FindControl(controlId);
                }
                else
                {
                    foundControl = page.FindControl(ctl);
                }
    
                if (!(foundControl is IButtonControl)) continue;
    
                control = foundControl;
                break;
            }
        }
    
        return control == null ? String.Empty : control.ID;
    }
    

    更新 (2016-07-22): 类型检查 ButtonImageButton 更改为查找 IButtonControl 以允许识别来自第三方控件的回发。

    【讨论】:

    • 感谢...完美的 sn-p 可重复使用。
    • 我有一个高级方案无法正常工作 - stackoverflow.com/questions/14486733/…
    • 如果有多个按钮或图像按钮,这不会失败吗?看起来它只会返回它找到的第一个。
    • 如果有多个按钮并且导致回发的按钮具有 UseSubmitBehavior="True" 则只有该按钮将包含在 HttpRequest.Form.AllKeys 中。如果 UseSubmitBehavior="False" 然后 __EVENTTARGET 将完成这项工作。
    • 如果导致回发的控件隐藏在容器中,那么您将无法使用页面对象上的 FindControl 方法找到它,而无需递归搜索子控件。
    【解决方案2】:

    要获得控件的确切名称,请使用:

        string controlName = Page.FindControl(Page.Request.Params["__EVENTTARGET"]).ID;
    

    【讨论】:

      【解决方案3】:

      除了之前的答案,要使用Request.Params["__EVENTTARGET"],您必须设置选项:

      buttonName.UseSubmitBehavior = false;
      

      【讨论】:

        【解决方案4】:
        if (Request.Params["__EVENTTARGET"] != null)
        {
          if (Request.Params["__EVENTTARGET"].ToString().Contains("myControlID"))
          {
            DoWhateverYouWant();
          }
        }
        

        【讨论】:

          【解决方案5】:

          如果您需要检查哪个控件导致了回发,那么您可以直接将["__EVENTTARGET"] 与您感兴趣的控件进行比较:

          if (specialControl.UniqueID == Page.Request.Params["__EVENTTARGET"])
          {
              /*do special stuff*/
          }
          

          这假设您只是要比较任何GetPostBackControl(...) 扩展方法的结果。它可能无法处理所有情况,但如果它有效,它会更简单。此外,您不会在页面中搜索您一开始并不关心的控件。

          【讨论】:

          • 这是一个不错的简单技巧。当我只想处理一些非常具体的控件的回发时,对我的情况有所帮助。
          【解决方案6】:

          直接在表单参数中或

          string controlName = this.Request.Params.Get("__EVENTTARGET");
          

          编辑:检查控件是否导致回发(手动):

          // input Image with name="imageName"
          if (this.Request["imageName"+".x"] != null) ...;//caused postBack
          
          // Other input with name="name"
          if (this.Request["name"] != null) ...;//caused postBack
          

          您还可以遍历所有控件并使用上述代码检查其中一个是否导致回发。

          【讨论】:

          • 那么,您必须了解所有可能导致回发的控件,并检查参数集合中是否有值 (Request[controlName])。
          • @JaroslavJandek 谢谢你的回答。我有一个实例,我需要在页面 OnLoad 事件期间检测按钮单击,但由于某种原因 Request["__EVENTTARGET"] 为空(即使它没有与其他控件导致回发。检查 Request[myButton. UniqueID] 完美运行。+1 :)
          【解决方案7】:

          这里有一些可能对你有用的代码(取自Ryan Farley's blog

          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;
          }
          

          【讨论】:

          • 我同意这个代码,我已经使用了一段时间了。
          • 这是正确的代码,我的答案是指PageUtility类,我完全忘记了这是我用上面的方法制作的一个类。
          【解决方案8】:

          假设是服务器控件,可以使用Request["ButtonName"]

          查看是否点击了特定按钮:if (Request["ButtonName"] != null)

          【讨论】:

          • Request[name] 对于所有异步回发都为空
          猜你喜欢
          • 1970-01-01
          • 2010-12-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多