如何让ValidationMessageFor工作? C#MVC4剃刀

时间:2016-11-17 04:11:59

标签: c# jquery asp.net-mvc asp.net-mvc-4 razor

模型

public class ViewModelA
{
    [Display(Name = "User Name")]
    [Required(ErrorMessage = "User Name Required")]
    public string UserName { get; set; }

    public ViewModelA() { }
}

查看

@using (Html.BeginForm("Register", "Account", FormMethod.Post))
{
    @Html.ValidationSummary()
    <div>@Html.LabelFor(m => m.UserName)</div>
    <div>@Html.TextBoxFor(m => m.UserName)</div>
    <div>@Html.ValidationMessageFor(m => m.UserName)</div>
    <div><input type="submit" value="SUBMIT" /></div>
}

控制器

[HttpPost]
public ActionResult Register(ViewModels.ViewModelA model)
{
    if (ModelState.IsValid)
    {
        // Do Something
    }
    else
    {
        // Do Something Else
    }

    ModelState.Clear();

    return View(model);
}

起初,我认为这是因为我没有jquery.validate.min.jsjquery.validate.unobtrusive.min.js但是我把它们包括在内并且没有做任何事情。然后我尝试了@Html.ValidationSummary()的混合。我在stackoverflow上看到的一切都说我所拥有的应该是有效的,但事实并非如此。我做错了什么?

1 个答案:

答案 0 :(得分:0)

不确定,但如果您删除了public ViewModelA() { }吗?

public class ViewModelA
{
    [Display(Name = "User Name")]
    [Required(ErrorMessage = "User Name Required")]
    public string UserName { get; set; }

    //public ViewModelA() { }
}

并删除ModelState.Clear();

[HttpPost]
public ActionResult Register(ViewModels.ViewModelA model)
{
    if (ModelState.IsValid)
    {
        // Do Something
    }
    else
    {
        // Do Something Else
    }

    //ModelState.Clear();

    return View(model);
}