6

在我看来,我有一个日期字段(用于 Jquery 日期选择器),

@if (Model != null)
{
  if (Model.SubmitStartDate == DateTime.MinValue)
  {
    Model.SubmitStartDate = null;
  }                    
  @Html.TextBoxFor(m => m.SubmitStartDate , new { @Id = "SubmitStartDate", @readonly = "readonly", @Value = @Model.SubmitStartDate})
} 

在我的模型中,我有:

[Required(ErrorMessage = "Please select a start date")]
[DisplayFormat(DataFormatString = "{0:d}")]
public DateTime? SubmitStartDate { get; set; }

但是在 UI 中,我得到10/07/2013 00:00:00 on load ,如何从中删除时间部分。我还需要格式为"dd-mm-yy" 的日期。有没有可能实现?

更新

我根据答案编辑了我的代码,并按要求工作,但是我遇到了问题。

当我使用@Html.EditorFor()我的readonly财产将不再工作。我也尝试DisplayFor过,但是它没有意义,因为我将它用于 J-query Date Picker。有什么办法可以使该字段只读?

更新代码:

@if (Model != null)
{
  if (Model.SubmitStartDate == DateTime.MinValue)
  {
    Model.SubmitStartDate = null;
  }                    
  @Html.EditorFor(m => m.SubmitStartDate , new { type = "date", @Id = "SubmitStartDate", @readonly = "readonly", @Value = @Model.SubmitStartDate})
} 
4

2 回答 2

16

您正在使用@Html.TextBoxFor()将忽略您的DisplayFormat属性的助手。将其更改为 a@Html.EditorFor()并应用您的 DisplayFormat。

并获得您的格式:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yy}")]
public DateTime? SubmitStartDate { get; set; }
于 2013-07-09T14:19:32.063 回答
0

这是我通常如何格式化数据注释以便在 chrome 和 IE 中工作。

[DisplayFormat(DataFormatString = "{0:yyyy-MM-dd}", ApplyFormatInEditMode = true)]
public DateTime StartDate { get; set; }

@Html.EditorFor(m => m.StartDate, new { type = "date" })
于 2013-07-09T14:22:54.483 回答