使用jQuery选择DropDownlist时如何防止AutoPostBack

我想在用户选择DropDownList中的项目时显示确认对话框。 如果用户按“取消”,我想停止回发。 这是我添加到onchange事件的函数:

function imitateConfirmUnload(event) { if (window.onbeforeunload = null) return true; return confirm("Are you sure you want to navigate away from this page?\n\nYou have unsaved changes\n\nPress OK to continue or Cancel to stay on the current page."); } 

这是我的启动脚本中的相关代码,用于向事件添加处理程序:

 function addConfirmToWarnClasses() { $('.warn').change(function() { imitateConfirmUnload() }); } 

问题是即使用户选择“取消”,也会发生回发。 如果我将处理程序移动到click事件,它就可以工作。 但我觉得很笨。

编辑

更正:它不起作用,因为对话框阻止选择,因此当用户选择“确定”时,没有发生任何更改,并且在您需要时没有回发!

编辑2

DropDownList位于UpdatePanel内部,因此可能会影响行为。

在阅读此解决方案后 ,我刚刚删除了DropDownLists上的AutoPostBack并使用了它,因为它非常简单:

 $("#DropDownList1").change(function (e) { if ($(this).val() == "0") { //do nothing } else { //do postback setTimeout("__doPostBack('DropDownList1','')", 0); } }); 

或者,如果您有多个DropDownLists您想要生成AutoPostBack

 $("select").change(function (e) { if ($(this).val() == "0") { //do nothing } else { //do postback setTimeout("__doPostBack('" + this.id + "','')", 0); } }); 

您还需要从该函数return ,如下所示:

 $('.warn').change(imitateConfirmUnload); 

目前没有使用return值。 这也有效:

 $('.warn').change(function() { return imitateConfirmUnload(); }); 

另外,我确定你想在这里进行等号检查:

 if (window.onbeforeunload == null) return true; 

目前它正在使onbeforeunload处理程序归零,如果它存在的话。

我知道这个问题有点陈旧,但是当我需要答案时它会在谷歌搜索中弹出,我会在这里发布解决方案。 我认为它比之前发布的更简单。

我从http://forums.asp.net/p/1475520/3432980.aspx获取它:

   

这里的关键部分是onchage中的代码:取消AutoPostBack它必须返回一些东西(无论是真还是假)并继续使用AutoPostBack它不应该返回任何东西。

果然,从更新面板取消异步回发需要不同的技术:

http://msdn.microsoft.com/en-us/magazine/cc163413.aspx

在UpdatePanel中从jQuery submit()中防止ASP.net __doPostback()

 //Adds an event handler to confirm unsaved changes when an asynchronous postback is initialised by an UpdatePanel function setConfirmAsyncPostBack() { if (typeof (Sys.WebForms) === "undefined" || typeof (Sys.WebForms.PageRequestManager) === "undefined") return; var prm = Sys.WebForms.PageRequestManager.getInstance(); prm.add_initializeRequest(confirmAsyncPostBack); } //An event handler for asynchronous postbacks that confirms unsaved changes, cancelling the postback if they are not confirmed //Adds the confirmation to elements that have a css class of "warn" function confirmAsyncPostBack(sender, args) { if (window.onbeforeunload != null && args.get_postBackElement().className == "warn" && !unloadConfirmed()) args.set_cancel(true); } //Displays a confirmation dialog that imitates the dialog displayed by onbeforeunload function unloadConfirmed() { var confirmed = confirm("Are you sure you want to navigate away from this page?\n\n" + unloadMessage() + "\n\nPress OK to continue or Cancel to stay on the current page."); if (confirmed) window.onbeforeunload = null; return confirmed; } function unloadMessage() { return 'You have unsaved changes.'; } 

此代码与我的另一个问题中描述的问题一致: DropDownList在AutoPostBack =“True”时未触发onb​​eforeunload