ASP.NET Custom Validator + WebMethod + jQuery

后端 未结 1 728
慢半拍i
慢半拍i 2020-12-10 18:00

I\'m trying to implement a .NET Custom Validator that uses $.ajax to query a WebMethod on the same page and return a boolean value to indicate whether the result is true or

相关标签:
1条回答
  • 2020-12-10 18:03

    The easy way is by changing your validate to:

     function validatePromo(src, args) {
        var isValid;
        $.ajax({
            type: "POST",
            url: "Register.aspx/IsPromoValid",
            data: "{'code': '" + args + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            async: false,
            success: function (msg) {
                 isValid = msg.d;
            }        
        });
        args.IsValid = isValid;
    }
    

    Take special note of the async:false. The reason your first try didn't work is that the ajax success callback was not getting called until after the validation scripts had already checked args.IsValid. With async:false, the $.ajax call won't complete until after the success callback is done.

    The big issue with this is that it now "blocks" whatever js thread is running the validation. In the case of ASP.Net validators, I don't believe this is an issue but I would test it with a long-running call just to make sure you aren't screwing up your page for anyone on a slow connection.

    0 讨论(0)
提交回复
热议问题