【问题标题】:Remote validation displaying red box but no error message? ASP - MVC 5远程验证显示红色框但没有错误消息? ASP-MVC 5
【发布时间】:2014-02-15 18:08:03
【问题描述】:

所以,我正在尝试对用户名和电子邮件使用自定义验证,但它正在工作但只给出一个红色框。它实际上并没有显示..这是我的代码

[Required]
    [Display(Name = "User name")]
    [System.Web.Mvc.Remote("UserExists", "Account", ErrorMessage = "UserName already exists, please pick another one.")]
    [Editable(true)]

控制器... 公共 JsonResult 用户存在(字符串用户名) {

        var user = UserManager.FindByName(UserName);

        return Json(!db.AspNetUsers.Any(x => x.UserName == UserName),
                                   JsonRequestBehavior.AllowGet);
    }

是的,它显示红色框,证明用户名存在,但实际上并未显示错误消息。如果我要提交,它将显示错误消息,否则不会。 这是模型。。

<script src="~/Scripts/jquery-2.0.3.js"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")" type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")" type="text/javascript"></script>
<fieldset>
    @Html.AntiForgeryToken()
    <h4>Create a new account.</h4>
    <hr />
    @Html.ValidationSummary()
    <div class="form-group">
        @Html.LabelFor(m => m.UserName, new { @class = "col-md-2 control-label" })
        <div class="col-md-10">
            @Html.TextBoxFor(m => m.UserName, new { @class = "form-control" })
            @Html.ValidationMessageFor(m => m.UserName)
        </div>

【问题讨论】:

  • 视图是什么样的?您实际上是否在输出错误消息,例如@Html.ValidationMessageFor(model =&gt; model.UserName)
  • 嘿,我已经更新了..

标签: c# asp.net asp.net-mvc json asp.net-mvc-5


【解决方案1】:

这就是你想要实现的功能:

public JsonResult UserExists(string UserName) {

    var user = UserManager.FindByName(UserName);
    if (!db.AspNetUsers.Any(x => x.UserName == UserName))
    return Json(true, JsonRequestBehavior.AllowGet);

   return Json(string.Format("{0} is not available", UserName) , JsonRequestBehavior.AllowGet);

}

将您的远程标签更新为:

[Remote("UserExists", "Account")]

这只是删除错误消息,基本上除了真正的返回之外的任何东西都是发送回客户端的错误消息。

更多信息可在此处获得:

http://msdn.microsoft.com/en-us/library/gg508808(v=vs.98).aspx

【讨论】:

  • 您好,为信息干杯,返回错误消息绝对是最好的主意。至于我原来的问题,它还在做。它仍然只给出一个红色框,然后在页面刷新后给出错误消息。
  • 好吧,我似乎已经修好了。显然“@Html.AntiForgeryToken()”正在阻止它给出错误消息。感谢您的帮助。
  • 确保将其添加到控制器顶部:[OutputCache(Location = OutputCacheLocation.None, NoStore = true)]
  • 谢谢,有人必须告诉我关于投票和接受的事情。 :)
猜你喜欢
  • 2011-09-11
  • 1970-01-01
  • 2016-05-08
  • 1970-01-01
  • 2017-01-06
  • 1970-01-01
  • 2014-09-23
  • 2017-03-11
  • 2016-07-10
相关资源
最近更新 更多