简体   繁体   中英

Prevent postback on button click and multiple client function

I have an asp.net button to update database

<asp:Button ID="btnSave" runat="server" Text="SaveChanges" OnClick="btnSave_Click"
        CssClass="saveButton" ValidationGroup="answer" OnClientClick="return ValidateUserNameBeforeSubmitting();" />

<script type="text/javascript">
    $(document).ready(function () {
        $("#<%=TextUserName.ClientID%>").blur(function () {
            ValidateUserNameAfterBlur();
        });
    });

    function ValidateUserName() {
        var returnValue;
        $.ajax({ type: "POST",
            url: "../UserNameWebService.asmx/ValidateUserName",
            data: JSON.stringify({ strUsername: $("#<%=TextUserName.ClientID%>").val() }), 
            contentType: "application/json; charset=utf-8",
            dataType: "json",

            async: false,
            success: function (data) {
                returnValue=data.d;
            },
            error: function (xhr, ajaxOptions, thrownError) {
                alert(xhr.status);
                alert(thrownError);
            }
        });
        return returnValue;
    }
    // to prevent postback when click save button. 
    function ValidateUserNameBeforeSubmitting() {
        var isValid = ValidateUserName();
        return isValid;
    }

    function ValidateUserNameAfterBlur() {
        var isValid = ValidateUserName();
        $('#TextUserNameError').toggle(!isValid);
    }
</script>

The function is to validate a textbox for an username. But I have a few textbox to be validated. Each one will display different error. Can I have multiple client side call on the button?

Thanks.

Of course you can have multiple client-side functions:

$("#<%=TextUserName.ClientID%>").blur(function () {
    ValidateUserNameAfterBlur();
    ValidatePasswordAfterBlur();
    ValidateFoo();
    PhoneYourWife();
    ...
});

If you want to submit only when they are all valids:

$("#<%=btnSave.ClientID%>").click(function () {
    if (ValidateUserNameAfterBlur() &&
        ValidatePasswordAfterBlur() &&
        ValidateFoo()               &&
        PhoneYourWife())

    submitTheData();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM