ASP.NET 自定义验证器 + Web方法 + jQuery

发布于 2024-09-28 05:23:12 字数 1253 浏览 0 评论 0原文

我正在尝试实现一个 .NET 自定义验证器,它使用 $.ajax 查询同一页面上的 WebMethod 并返回一个布尔值来指示结果是 true 还是 false。

我使用的 WebMethod 非常简单

[WebMethod()]
public static bool IsPromoValid(string code)
{
    string promoCode = "ABCDEFG";
    bool result = code.ToLower() == promoCode.ToLower();
    return result;
}

CustomValidator 看起来像这样

<asp:CustomValidator ID="cvPromoCode" Display="None" ControlToValidate="txtPromoCode" runat="server" ClientValidationFunction="validatePromo"
    ErrorMessage="The promo code you entered is incorrect" OnServerValidate="ValidatePromoCode" />

和简单的 $.ajax() ClientValidation 函数

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

问题在于页面立即验证,实际上并不等待 ajax 调用完成。如果页面上存在任何其他错误,它会显示验证摘要,但不会显示来自自定义验证器的错误消息。

我可以看到在 Firebug 中进行 AJAX 调用,并且它返回正确的响应(在本例中为 truefalse

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 false.

The WebMethod I'm using is really simple

[WebMethod()]
public static bool IsPromoValid(string code)
{
    string promoCode = "ABCDEFG";
    bool result = code.ToLower() == promoCode.ToLower();
    return result;
}

The CustomValidator looks like this

<asp:CustomValidator ID="cvPromoCode" Display="None" ControlToValidate="txtPromoCode" runat="server" ClientValidationFunction="validatePromo"
    ErrorMessage="The promo code you entered is incorrect" OnServerValidate="ValidatePromoCode" />

And the simple $.ajax() ClientValidation function

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

The problem is that the page validates instantly and doesn't actually wait for the ajax call to finish. If there are any other errors on the page, it shows the Validation Summary with them, but never shows the error message from the Custom Validator.

I can see the AJAX call being made in Firebug, and it returs the right response (in this case true or false)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

不念旧人 2024-10-05 05:23:12

简单的方法是将验证更改为:

 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;
}

特别注意async:false。您的第一次尝试不起作用的原因是,直到验证脚本已经检查了 args.IsValid 之后,才调用 ajax 成功回调。使用 async:false 时,$.ajax 调用只有在成功回调完成后才会完成。

最大的问题是它现在“阻止”任何正在运行验证的 js 线程。对于 ASP.Net 验证器,我不认为这是一个问题,但我会通过长时间运行的调用来测试它,以确保您不会为连接速度慢的任何人搞砸页面。

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文