DisplayFormat Dataannotation不工作 [英] DisplayFormat Dataannotation not working

查看:139
本文介绍了DisplayFormat Dataannotation不工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的模型类以下dataannotation:

I have following dataannotation in my model class:

[Required(ErrorMessage = "Required")]
    [DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MM/dd/yyyy}")]
    public DateTime DateOfBirth { get; set; }

,当我在我看来使用后,我没有得到验证错误:

and when I use following in my view, I dont get validation error:

 <tr>
        <td>@Html.LabelFor(x => x.DateOfBirth, new { @class = "lbl" }, "Date Of Birth") </td>
        <td>@Html.TextBoxFor(x => x.DateOfBirth, new { @class = "w100 _dob" })
        <br>@Html.ValidationMessageFor(x => x.DateOfBirth)
        </td>

</tr>

您可以请建议解决?

推荐答案

DisplayFormat 属性无关与验证。它仅用于在视图中显示时,格式化值。如果您想验证正由在相应的输入字段的用户输入的值,你将不得不编写自定义模型粘合剂。

The DisplayFormat attribute has nothing to do with validation. It is used only to format the value when displayed on a view. If you want to validate that the value that is being entered by the user in the corresponding input field you will have to write a custom model binder.

和顺便DisplayFormat属性与Html.EditorFor辅助结合使用,而且它与Html.TextBoxFor帮手严格没有影响这是你使用的是什么:

And by the way the DisplayFormat attribute is used in conjunction with the Html.EditorFor helper and it has strictly no effect with the Html.TextBoxFor helper which is what you are using:

<tr>
    <td>
        @Html.LabelFor(x => x.DateOfBirth, "Date Of Birth")
    </td>
    <td>
        @Html.EditorFor(x => x.DateOfBirth)
        <br/>
        @Html.ValidationMessageFor(x => x.DateOfBirth)
    </td>
</tr>

这篇关于DisplayFormat Dataannotation不工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆