Asp.net 使用jQuery选择DropDownlist时如何防止自动回发

Asp.net 使用jQuery选择DropDownlist时如何防止自动回发,asp.net,jquery,javascript-events,Asp.net,Jquery,Javascript Events,我想在用户选择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\nYo

我想在用户选择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事件,它就会工作。但我觉得它很笨重

编辑

更正:onclick不起作用,因为对话框阻止选择,所以当用户选择OK时,不会发生任何更改,并且在需要时不会回发

编辑2


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

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

$('.warn').change(imitateConfirmUnload);
当前未使用
返回值
。这也将有助于:

$('.warn').change(function() {
  return imitateConfirmUnload();
});
另外,我很确定你想要一个相等的检查:

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

当前,如果存在
onbeforeunload
处理程序,它将清空该处理程序。

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

这段代码与我的另一个问题中描述的问题一致:

阅读后,我刚刚删除了我的
下拉列表上的
自动回发
,并使用它,因为它非常简单:

$("#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);
    }
});

我知道这个问题有点老了,但因为当我需要答案时,它会在谷歌搜索中出现,所以我会在这里发布解决方案。我认为这比以前贴的要简单

我是从:


函数stopPostback()
{
如果(布拉布拉赫)
返回true;//停止回发
返回false;
}

这里的关键部分是onchage中的代码:要取消自动回邮,它必须返回一些内容(不管是真是假),要继续进行自动回邮,它不应该返回任何内容。

谢谢您的回答。它很快发现了两个问题。我想这会解决的。令人惊讶的是,事实并非如此。回发仍然发生。DropDownList在UpdatePanel中,所以我想知道这是否会影响行为…?@Colin-是的,绝对会。UpdatePanel完全改变了游戏,它在尝试发布时由Microsoft脚本捕获和处理。您应该尝试将标记与行为分离。看到这一点:Javascript事件作为内联属性不再存在于我的脑海中。Nick Craver的代码很好,但由于UpdatePanel,它不是公认的答案
$("select").change(function (e) {
    if ($(this).val() == "0") {
        //do nothing
    }
    else {
        //do postback
        setTimeout("__doPostBack('" + this.id + "','')", 0);
    }
});
<script type="text/javascript">
    function stopPostback()
    {
        if (blahblah)
            return true; // stop postback


        return false;
    }
</script>

<asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True" onchange="if (stopPostback()) return false;">