更改后保留MVC远程验证错误

时间:2014-12-12 16:27:38

标签: asp.net-mvc-4 remote-validation

我在给出无效的电子邮件后第二次进行远程验证检查时遇到问题。我无法弄清楚为什么它在不再无效之后不会删除错误。

这是我的模特:

[Required(ErrorMessage = "An email is required")]
[StringLength(150, MinimumLength = 4)]
[Display(Name = "Email")]
[RegularExpression("^([a-zA-Z0-9_\\-\\.]+)@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.)|(([a-zA-Z0-9\\-]+\\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\\]?)$", ErrorMessage = "Invalid Email")]
[Remote("doesEmailExist", "Account", HttpMethod = "POST", ErrorMessage = "This email has already registered. Please use a different email")]
public virtual string strEmail { get; set; }

我的观点:

<ul>
        <li class="editor-label">@Html.LabelFor(m => m.strEmail)</li>
        <li class="editor-field">@Html.TextBoxFor(m => m.strEmail)</li>
        <li class="error">@Html.ValidationMessageFor(m => m.strEmail)</li>
</ul>

我的控制器:

[HttpPost]
public JsonResult doesEmailExist(string strEmail)
    {

        var user = db.t_user.FirstOrDefault(i => i.email == strEmail);
        if (user == null)
            return Json(null);
        else
            return Json(false);

    }

为什么远程验证没有纠正自己从无效条目到有效条目?

1 个答案:

答案 0 :(得分:0)

如果不存在现有电子邮件,则JsonReturn需要返回true(而不是null)。注意这应该是一个GET

[HttpGet]
public JsonResult doesEmailExist(string strEmail)
{
  var user = db.t_user.FirstOrDefault(i => i.email == strEmail);
  if (user == null)
    return Json(true, JsonRequestBehavior.AllowGet); // change this
  else
     return Json(false, JsonRequestBehavior.AllowGet);

}

 bool exists = db.t_user.Any(i => i.email == strEmail)
 return Json(!exists, JsonRequestBehavior.AllowGet);

另请注意,您可以使用[EmailAddress]代替[RegularExpression]属性