在页面初始化事件中,如何检查哪个控件导致了回发?

64

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

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

}

感谢

8个回答

119

我看到已经有一些非常好的建议和方法可以帮助恢复Post Back控件。但是我在另一个网页(Mahesh博客)上找到了一种检索Post Back控件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 ,以允许识别来自第三方控件的 postbacks。


3
谢谢。这是完美的代码片段,可以重复使用。 - Anthony Graglia
1
我有一个高级场景,它无法正常工作 - https://dev59.com/9mYq5IYBdhLWcg3wcgHq - LCJ
5
如果存在多个按钮或图像按钮,这种方法是否会失败?看起来它只会返回它找到的第一个按钮。 - Mike Fulton
7
如果有多个按钮且触发postback的按钮UseSubmitBehavior="True",那么只有这个按钮会被包含在HttpRequest.Form.AllKeys中。如果UseSubmitBehavior="False",那么__EVENTTARGET将会起作用。 - user764754
2
如果引起回发的控件被嵌套在一个容器中,那么你不能仅通过在页面对象上使用FindControl方法来找到它,而需要递归地搜索子控件。 - Daniel Przybylski
显示剩余4条评论

17

以下代码可能对你有所帮助(来自Ryan Farley的博客

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

1
我批准这段代码,我已经使用它一段时间了。 - Alex
这是正确的代码,我的答案涉及到PageUtility类,我完全忘记了它是我用上面的方法创建的一个类。 - Alex

11

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

如果您需要检查哪个控件引起了页面回发,则可以直接将["__EVENTTARGET"]与您感兴趣的控件进行比较:

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

假设您只是要比较任何GetPostBackControl(...)扩展方法的结果。 这种方法可能无法处理每种情况,但如果它有效,则更简单。 此外,您不必搜索页面以寻找起初并不关心的控件。


这是一个不错且简单的技巧。在我需要处理某些非常特定控件的回发时,它帮了我大忙。 - Marcel

10

无论是直接在表单参数中还是

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

你也可以通过遍历所有控件并使用上述代码检查它们中的任何一个是否引起了postBack来实现。


那么,您必须了解可能导致回发的所有控件,并检查参数集合中是否有值(Request[controlName])。 - Jaroslav Jandek
@JaroslavJandek 谢谢您的回答。我曾经遇到这样一个情况,需要在页面 OnLoad 事件中检测按钮点击,但是 Request["__EVENTTARGET"] 却为空,尽管其他控件引起 postback 时该值不为空。对 Request[myButton.UniqueID] 的检查完全有效。 +1 :) - KP.

4
if (Request.Params["__EVENTTARGET"] != null)
{
  if (Request.Params["__EVENTTARGET"].ToString().Contains("myControlID"))
  {
    DoWhateverYouWant();
  }
}

3
假设这是一个服务器控件,你可以使用 Request["ButtonName"]。 要查看特定按钮是否被点击:if (Request["ButtonName"] != null)

3
所有异步后台回发的“Request[name]”均为null。 - Fredrick Gauss

2

在之前的答案基础上,要使用Request.Params["__EVENTTARGET"],您需要设置选项:

buttonName.UseSubmitBehavior = false;

1
获取控件的确切名称,请使用:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接