如何判断ASP中的页面卸载是否为回发 [英] How to tell if a page unload in ASP is a PostBack
问题描述
这似乎是一个常见问题,但搜索未返回任何内容.
This seems like a common question but search is not returning anything.
我有以下代码在页面卸载之前执行.问题是如果卸载是回发,我不想向用户发出警告,但我不知道如何区分回发和例如,用户导航到另一个页面.
I have the following code that executes before the page unloads.The problem is if the unload is a postback i do not want to fire my warning to the user but i can't figure out how to differentiate between a postback and a user navigating to another page for example.
// This is executed before the page actually unloads
$(window).bind("beforeunload", function () {
if (prompt) {
//prompt
return true;
}
else {
//reset our prompt variable
prompt = true;
}
})
在代码背后运行脚本,即如果Page.IsPostBack然后设置提示不是选项.
Running script in the code behind i.e. if Page.IsPostBack then set prompt is not an option.
有什么想法吗?
这是我最终得到的解决方案:
Here is the solution I ended up with:
function DoNotPrompt() {
prompt = false;
}
然后我将其添加到所有控件中,用户可以在这些控件中做一些会导致回发的操作.
I then added this to all the controls where the user could do something that result in a post back.
OnClientClick="DoNotPrompt()
然后检查此标志,如果用户确实离开页面即不回发,则仅在"beforeunload"中返回字符串.
Then checked this flag and only returned a string in "beforeunload" if the user was really moving away from the page i.e. not a postback.
我还必须使用以下代码: var magicInput = document.getElementById('__ EVENTTARGET');
I also had to use this code: var magicInput = document.getElementById('__EVENTTARGET');
if (magicInput && magicInput.value) {
// the page is being posted back by an ASP control
prompt = false;
}
原因是我有一个自定义用户控件,该控件是一个列表框,因此我无法添加上述方法.因此,用它来捕获该事件并将标志设置为false.
The reason being i had a custom user control that was a list box and I could not add the above method. So used this to catch that event and set the flag to false.
不是最精致的解决方案.
Not the most elegent solution.
谢谢, 迈克尔
推荐答案
这可能无法涵盖所有回发情况,但是您可以通过查询__EVENTTARGET
隐藏输入来判断页面是否由ASP控件回发了.
This may not cover all of the postback situations, but you can tell if the page was posted back by an ASP control by interrogating the __EVENTTARGET
hidden input.
当ASP控件将页面发回时,此输入由ASP设置.
This input is set by ASP when the page is posted back by an ASP control.
var magicInput = document.getElementById('__EVENTTARGET');
if (magicInput && magicInput.value) {
// the page is being posted back by an ASP control
}
这篇关于如何判断ASP中的页面卸载是否为回发的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!