使用“[DataType(DataType.Text)]”时如何在模型中声明日期格式样式

How to declare date format style in model when `[DataType(DataType.Text)]` is used

通常,当我在我的模型中将 [DisplayFormat(DataFormatString="{0:d}")] 属性与 DateTime 属性 一起使用时,DateTime 值仅正确显示日期部分。

但是,因为 Edge(而且只有 Edge)覆盖了 Bootstrap 日期选择器以显示它自己的日期选择器,所以我必须将我的属性更改为以下内容(在我的模型中显示一个 属性 作为例子):

[Required]
[Display(Name="Start Date")]
[DataType(DataType.Text)]  // this is required to make Bootstrap 
                           // datepicker work with Edge
[DisplayFormat(DataFormatString="{0:d}")] // this attribute is now ignored
public DateTime? SelectedStartDate { get; set; }

换句话说,我必须将 DateTime 字段声明为文本,所以当我的页面呈现时,它看起来像这样。

当用户选择日期时,会显示正确的格式,以便确定该部分。

<script>
  $(function () {
      var formatparam = {format:"mm/dd/yyyy", setDate: new Date(), autoclose: true };
      $("#SelectedStartDate").datepicker(formatparam);
      $("#SelectedEndDate").datepicker(formatparam);
  });
</script>

我是否可以在模型或脚本块中声明一些内容,以便默认值仅显示为日期而不显示为日期时间?

鉴于 SelectedStartDate 将为字符串

@string.Format("{0:d}", Model.SelectedStartDate)

我经历了几次范式转变和重构。感谢@Steven Muecke 的建议。

在早期的迭代中,我曾尝试 @Html.TextBoxFor(m => m.SelectedStartDate) 但没有成功。我不知道的是我还需要添加格式字符串,所以它看起来像这样:

@Html.TextBoxFor(m => m.SelectedStartDate, "{0:d}")

所以我的模型更干净了:

[Required]
[Display(Name="Start Date")] 
[DisplayFormat(DataFormatString="{0:d}")]
public DateTime? SelectedStartDate { get; set; }

现在的行为正是我所需要的:默认视图被格式化为仅日期而不是日期时间。