从客户端处理程序返回 false 不会阻止回发

Returning false from Client-Side Handler does not Prevent Postback

本文关键字:false 客户端 处理 程序 返回      更新时间:2023-09-26

我在WebForms页面上有以下按钮:

<asp:Button ID="btnNewProgramNext" runat="server" Text="Next &gt;&gt;" />

我有以下javascript/jquery来处理它的事件。

$('#<%= btnNewProgramNext.ClientID %>').on('click', function (e) {
    var errorMessage = '';
    var ok = false;
    var newCompany = $('#<%= NewCompanyMode.ClientID %>').val();
    if (newCompany == 1) {
        if (!$('#<%= txtProgramCompanyName.ClientID %>').val())
            errorMessage = 'You must enter a company name.';
        else if (!$('#<%= txtContactFirstName.ClientID %>').val())
            errorMessage = 'You must enter a contact first name.';
        else if (!$('#<%= txtContactLastName.ClientID %>').val())
            errorMessage = 'You must enter a contact last name.';
        else
            ok = true;
    }
    else {
        // Do something else
        ok = true;
    }
    $('#newProgramErrorMessage').text(errorMessage);
    return ok;
});

问题是,当此处理程序返回 false 时(当 ok 为 false 时,或者当我将最后一行更改为 return false 时),回发仍然会发生。

有什么技巧可以防止从javascript回发吗?我希望这能奏效。

你需要 e.preventDefault() 来取消按钮单击事件。

$('#<%= btnNewProgramNext.ClientID %>').on('click', function (e) {
    var errorMessage = '';
    var ok = false;
    var newCompany = $('#<%= NewCompanyMode.ClientID %>').val();
    if (newCompany == 1) {
        if ($('#<%= txtProgramCompanyName.ClientID %>').val() == "")
            errorMessage = 'You must enter a company name.';
        else if ($('#<%= txtContactFirstName.ClientID %>').val() == "")
            errorMessage = 'You must enter a contact first name.';
        else if ($('#<%= txtContactLastName.ClientID %>').val() == "")
            errorMessage = 'You must enter a contact last name.';
        else
            ok = true;
    } else {
        // Do something else
        ok = true;
    }
    if (!ok) {
        e.preventDefault();
        $('#newProgramErrorMessage').text(errorMessage);
    }
    // else everything is valid, so post back to server.
});

为什么不尝试通过 ClientClick 属性连接它,而不是使用 jQuery 订阅点击事件。 这可能是 ASP.NET 用来确定是否终止回发的路由。