DisplayAttribute关闭验证消息

时间:2011-04-25 20:03:35

标签: asp.net-mvc validation

所以当我有一个DisplayAttribute在我的一个模型中装饰一个属性时......

[Required, Display(Name = "Some Name")]
public string SomeProperty { get; set; }

使用ValidationMessageFor帮助程序

时,我不再收到该字段的验证消息
@Html.ValidationMessageFor(model => model.SomeProperty)

奇怪的是,如果我使用指定消息的重载,我仍然没有收到消息。有谁知道这里发生了什么?

1 个答案:

答案 0 :(得分:0)

无法复制。

型号:

public class MyViewModel
{
    [Required, Display(Name = "Some Name")]
    public string SomeProperty { get; set; }
}

控制器:

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

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

查看:

@model MyViewModel
@using (Html.BeginForm())
{
    @Html.LabelFor(x => x.SomeProperty)
    @Html.EditorFor(x => x.SomeProperty)
    @Html.ValidationMessageFor(x => x.SomeProperty)
    <input type="submit" value="OK" />
}

提交表单时,如果该字段留空,则会正确显示验证错误消息。