ASP.NET Custom Validator + WebMethod + jQuery

旧时模样 提交于 2019-11-28 11:24:18

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!