如何检查UpdatePanel是否正在进行回发?

12

有没有一种方法可以确定一个 <asp:UpdatePanel /> 是否执行了类似于我们可以使用的Ajax postback...

if(!Page.IsPostBack) { ...snip }

我希望确定是否发生了来自按钮提交的后台提交。

我正在尝试检测来自jQuery的Ajax请求,但它也会捕获UpdatePanel请求,而我想要排除它们,例如...

if (Request.IsAjaxRequest() && !Page.IsUpdatePanelPostback)
{
    // Deal with jQuery Ajax
}
3个回答

18
您可以通过查看这些属性来检查回发是否是异步的,以及是否由更新面板发出:
ScriptManager.GetCurrent(Page).IsInAsyncPostBack
ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID

16

我不知道这个解决方案是否比你的更好,但你尝试过了吗?

if (ScriptManager.GetCurrent(Page).IsInAsyncPostBack)
{
    Control ctrl = GetControlThatCausedPostBack(Page);
    if (ctrl is UpdatePanel)
    {
        //handle updatepanel postback
    }
}

private Control GetControlThatCausedPostBack(Page page)
{
    //initialize a control and set it to null
    Control ctrl = null;

    //get the event target name and find the control
    string ctrlName = Page.Request.Params.Get("__EVENTTARGET");
    if (!String.IsNullOrEmpty(ctrlName))
        ctrl = page.FindControl(ctrlName);

    //return the control to the calling method
    return ctrl;
}

我在想是否可以单独使用“ScriptManager.GetCurrent(Page).IsInAsyncPostBack”,因为我猜测ASP.NET AJAX扩展中的其他控件可能会触发我不想捕获的Ajax请求。 - Sunday Ironfoot
我想试一试,也许值得一试。 - James Johnson
使用ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID - Bolo

3

尝试以下操作:

var controlName = Page.Request.Params.Get("__EVENTTARGET");
if (!String.IsNullOrEmpty(controlName))
{
     // Use FindControl(controlName) to see whether 
     // control is of UpdatePanel type
}

有用的链接:


可能会起作用,但它只检测特定的UpdatePanel,是吗?我需要一个更“通用”的解决方案,可以检测任何UpdatePanel。 - Sunday Ironfoot
没问题,你可以使用FindControl()来查看这个控件是否是UpdatePanel类型的...我已经更新了我的答案。 - sll

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