asp.net mvc 3远程验证问题

时间:2011-04-06 19:14:25

标签: asp.net-mvc validation asp.net-mvc-3

这是我的模特:

    [Required(ErrorMessage = "Email required!")]
    [Remote("EmailExists","User",ErrorMessage = "Email already")]
    public virtual string Email { get; set; }

查看:

    @Html.TextBoxFor(x => x.Email)
    @Html.ValidationMessageFor(x => x.Email)

控制器:

    public ActionResult EmailExists(string Email)
    {
         return Json(!Email.Equals("teste@gmail.com"), 
                                      JsonRequestBehavior.AllowGet);
    }
添加了

jquery.validate.min.jsjquery.validate.unobtrusive.min.js。并且web.config也已配置。

当我输入电子邮件输入时,它会触发EmailExists罚款。同样返回true / false。 但是它显示了ErrorMessage

我收到了这个错误:

 Erro: uncaught exception: 
 [Exception... "Cannot modify properties of a WrappedNative"
 nsresult: "0x80570034 (NS_ERROR_XPC_CANT_MODIFY_PROP_ON_WN)"  
 location: "JS frame :: chrome://global/content/bindings/autocomplete.xml ::
 onxblpopuphiding :: line 848"  data: no]

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

您的描述中没有任何内容可以解决问题。我使用默认模板创建了一个新的ASP.NET MVC 3应用程序,添加了模型:

public class MyViewModel
{
    [Required(ErrorMessage = "Email required!")]
    [Remote("EmailExists", "Home", ErrorMessage = "Email already")]
    public string Email { get; set; }
}

更新了HomeController

public class HomeController: Controller
{
    public ActionResult Index()
    {
        return View(new MyViewModel());
    }

    [HttpPost]
    public ActionResult Index(MyViewModel model)
    {
        return View(model);
    }

    public ActionResult EmailExists(string Email)
    {
        return Json(
            !Email.Equals("teste@gmail.com"), 
            JsonRequestBehavior.AllowGet
        );
    }
}

~/Views/Home/Index.cshtml视图:

@model AppName.Models.MyViewModel
<script type="text/javascript" src="@Url.Content("~/scripts/jquery.validate.min.js")"></script>
<script type="text/javascript" src="@Url.Content("~/scripts/jquery.validate.unobtrusive.min.js")"></script>
@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.Email)
    @Html.TextBoxFor(x => x.Email)
    @Html.ValidationMessageFor(x => x.Email)
    <input type="submit" value="OK" />
}

验证触发正常并显示正确的错误消息(使用Chrome 10.0,IE9和FireFox 4.0进行测试)。所以现在的问题是你的场景与这个场景有何不同?

答案 1 :(得分:0)

你只需要这样做:

    [Required(ErrorMessage = "Email required!")]
    [Remote("EmailExists","User")]
    public virtual string Email { get; set; }

    public JsonResult EmailExists(string Email)
    {
        string errorMessage = "Email already";
        if (!Email.Equals("teste@gmail.com"))
            return Json(true, JsonRequestBehavior.AllowGet);

        return Json(errorMessage, JsonRequestBehavior.AllowGet);
    }