ASP.NET MVC 数据注释日期时间默认值

发布于 2024-10-06 07:45:19 字数 716 浏览 0 评论 0原文

在我的 ViewModel 中,我有以下属性:

[Required]
[DataType(DataType.Date, ErrorMessage = "Please enter a valid date in the format dd/mm/yyyy")]
[Display(Name = "Date of Birth")]
public DateTime DOB { get; set; }

在我的 View 中,我有以下属性:

<div class="editor-label">
    @Html.LabelFor(model => model.DOB)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.DOB)
    @Html.ValidationMessageFor(model => model.DOB)
</div>

在提交表单之前,DOB 的默认值为 1/01/0001,如何阻止自动填充此值,当人们访问此表单时我只想一个空字段?

In my ViewModel I have the following attribute:

[Required]
[DataType(DataType.Date, ErrorMessage = "Please enter a valid date in the format dd/mm/yyyy")]
[Display(Name = "Date of Birth")]
public DateTime DOB { get; set; }

In my View I have the following:

<div class="editor-label">
    @Html.LabelFor(model => model.DOB)
</div>
<div class="editor-field">
    @Html.EditorFor(model => model.DOB)
    @Html.ValidationMessageFor(model => model.DOB)
</div>

Before submitting the form the default value for DOB is 1/01/0001, how do I stop this value from being auto-populated, I simply want an empty field when people visit this form?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

溺深海 2024-10-13 07:45:19

我相信您将不得不使用可为空的 DateTime?类型。 DateTime 不能为 null,因此它始终有一个值。

I believe you will have to use the nullable DateTime? type. DateTime cannot be null thus it will always have a value.

土豪 2024-10-13 07:45:19

尝试使 DOB DateTime 可为空,如 @Mayo 所说:

public DateTime? DOB { get; set; }

Try making the DOB DateTime nullable like @Mayo states:

public DateTime? DOB { get; set; }
止于盛夏 2024-10-13 07:45:19

DateTime 是结构体类型。因此,默认情况下 DateTime 不能为 null。它的默认值等于“01/01/0001”。
您的问题的解决方案是使用可为空的 DateTime?类型。
如果您希望它默认为“01/01/2014”等某个值,那么您可以分配如下值:
DOB = 新的日期时间(2014, 01, 01);

DateTime is of type struct. So, by default DateTime cannot be null. It has default value equal to '01/01/0001'.
Solution to your problem is to use the nullable DateTime? type.
If you want it to default to some value like '01/01/2014', then you can assign value like:
DOB = new DateTime(2014, 01, 01);

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文