asp.net-mvc-4 – 使用EditorFor显示默认值的空编辑器

我的模特有一个属性:

[Required]
[DataType(DataType.Date)]
public DateTime BirthDate { get; set; }

我使用EditorFor在我的(强类型)视图中显示:

<p>@Html.LabelFor(m => m.BirthDate)
   @Html.EditorFor(m => m.BirthDate)
   @Html.ValidationMessageFor(m => m.BirthDate)
</p>

呈现视图时,出生日期文本框显示“01.01.0001”,即DateTime默认值.如果未初始化BirthDate值,这是正确的,但是在这种情况下我希望文本框为空.

这样做的标准方法是什么?我不想使用Nullable< DateTime>在我的模型中,因为BirthDate是必需值.

最佳答案 您最有可能寻找
DisplayFormat属性.另外,除非你使用的是DateTime?/ Nullable< DateTime>你可能最终会在1月1日结束(因为不能有空值).

如果你决定使用DateTime?/ Nullable< DateTime>使用[必需]执行一个值应该避免你说的任何问题,所以如果那是你的犹豫,我不会太担心.

作为最后的替代方法,您可以覆盖DateTime.cshtml(或Date.cshtml,因为您使用的是DataType属性)模板(〜/ Views / Shared / DisplayTemplates /),并在填充默认值(DateTime)时使文本框为空.例如

@model DateTime
@Html.TextBox(String.Empty, Model == default(DateTime) ? String.Empty : Model)

(或类似的规定)

点赞