【问题标题】:Return a warning (not an error) via Ajax remote validation通过 Ajax 远程验证返回警告(不是错误)
【发布时间】:2016-11-18 00:15:08
【问题描述】:

我有一个 MVC Ajax 回调来检查用户输入是否有效。此回调通过关联模型属性上的 [Remote] 属性调用。

我已经更改了我的设计,并且我决定如果值不正确,我真的想警告用户,但我不希望不正确的值阻止模型验证。

快速搜索会找到几个线程,这些线程描述了连接“不引人注目的警告”的一般问题的非常复杂的解决方案,类似于 MVC 中的“不引人注目的验证”魔法(例如 this SO post)。我不是在寻找一个通用的解决方案,我不想在这上面花费很多时间和精力,但是我想知道是否有一些 Ajax 大师知道我可以从 Ajax 服务器例程返回的东西导致不显眼的验证客户端代码在不触发验证错误的情况下放置消息的效果。

仅供参考,我现有的服务器端代码如下所示:

    public async Task<ActionResult> CouponCodeExists(string couponCode, int? planId)
    {
        if (some_logic) {
            return Json("Coupon code is already taken", JsonRequestBehavior.AllowGet);
        } else {
            return Json(true, JsonRequestBehavior.AllowGet);
        }
    }

【问题讨论】:

  • 只需在输入.change() 事件中进行自己的ajax 调用,并在成功回调中显示消息(如果您不希望它触发验证错误,请删除RemoteAttribute
  • @StephenMuecke 没有更好的答案,我愿意接受您的评论作为首选答案。如果您愿意将其发布为“答案”,我会接受并完成这个问题。

标签: ajax asp.net-mvc validation


【解决方案1】:

RemoteAttribute 是一个验证属性,触发它将向jQuery.validate.js 添加一个验证错误并阻止表单提交。如果您只想要一条警告消息,并且仍然允许提交表单,您可以在输入 .change() 事件中进行自己的 ajax 调用。

假设您在视图中有@Html.TextBoxFor(m =&gt; m.couponCode),请为消息添加一个占位符 - 例如&lt;div id="couponwarning"&gt;Coupon code is already taken&lt;/div&gt;,并将样式设置为display: none;。然后添加以下脚本

var url = '@Url.Action("CouponCodeExists")';
var warning = $('#couponwarning');
$('#couponCode').change(function() {
    var code = $(this).val();
    var id = .... // the value of your planId input?
    $.get(url, { couponCode: code, planId: id }, function(response) {
        if (response) {
            warning.show();
        }
    });
});
$('#couponCode').keyup(function() {
    warning.hide();
});

并且该方法可以只返回true来显示消息,或者null

if (some_logic) {
    return Json(true, JsonRequestBehavior.AllowGet);
} else {
    return Json(null, JsonRequestBehavior.AllowGet);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-05
    • 1970-01-01
    • 1970-01-01
    • 2015-02-22
    相关资源
    最近更新 更多