如何判断 ASP 中的页面卸载是否为 PostBack

Mic*_*ood 5 javascript asp.net jquery

这似乎是一个常见问题,但搜索没有返回任何内容。

我有以下在页面卸载之前执行的代码。问题是如果卸载是回发,我不想向用户发出警告,但我无法弄清楚如何区分回发和导航到的用户例如另一个页面。

// This is executed before the page actually unloads
        $(window).bind("beforeunload", function () {

            if (prompt) {

                //prompt
                return true;
            }
            else {

                //reset our prompt variable
                prompt = true;
            }
        })
Run Code Online (Sandbox Code Playgroud)

在后面的代码中运行脚本,即如果 Page.IsPostBack 然后设置提示不是一个选项。

有任何想法吗?

编辑:

这是我最终得到的解决方案:

 function DoNotPrompt() {
              prompt = false;
        }
Run Code Online (Sandbox Code Playgroud)

然后我将它添加到所有控件中,用户可以在其中执行一些导致回发的操作。

OnClientClick="DoNotPrompt()
Run Code Online (Sandbox Code Playgroud)

然后检查这个标志,如果用户真的离开页面,即不是回发,则只在“beforeunload”中返回一个字符串。

我还必须使用以下代码: var magicInput = document.getElementById('__EVENTTARGET');

    if (magicInput && magicInput.value) {
        // the page is being posted back by an ASP control 
        prompt = false;
    }
Run Code Online (Sandbox Code Playgroud)

原因是我有一个自定义用户控件,它是一个列表框,我无法添加上述方法。所以用它来捕获该事件并将标志设置为 false。

不是最优雅的解决方案。

谢谢,迈克尔

jba*_*bey 1

这可能无法涵盖所有​​回发情况,但您可以通过询问__EVENTTARGET隐藏输入来判断页面是否是由 ASP 控件回发的。

当 ASP 控件回发页面时,该输入由 ASP 设置。

var magicInput = document.getElementById('__EVENTTARGET');

if (magicInput && magicInput.value) {
   // the page is being posted back by an ASP control
}
Run Code Online (Sandbox Code Playgroud)