【问题标题】:How do I show the DateTime in the view using the DataType.Date data annotation?如何使用 DataType.Date 数据注释在视图中显示 DateTime?
【发布时间】:2019-10-03 02:16:02
【问题描述】:

我在从我的模型中获取 DateTime 对象以显示在日期时间选择器中时遇到问题。 最初,我使用 DisplayFormat DataAnnotation 将其视为具有特定格式的文本。

我已尝试添加 DataType DataAnnotation。 我尝试添加所需的 DataAnnotation 我已尝试将 DisplayFormat 更改为 dd/MM/yyyy。

我见过datatype.date annotation not showing calendar in firefox,并已使用最新版本的 Chrome 和 Firefox 进行了测试。

原始 Billing.cs

[DataMember]
[Display(Name = "Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy MMM dd}")]
public System.DateTime StartDate { get; set; }

使用 Billing.cs 测试

[DataMember]
[Display(Name = "Start Date")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd/MM/yyyy}")]
[DataType(DataType.Date), Required]
public System.DateTime StartDate { get; set; }

编辑.cshtml

<div class="form-group row">
    @Html.LabelFor(model => model.StartDate, htmlAttributes: new { @class = "col-form-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.StartDate, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.StartDate, "", new { @class = "text-danger" })
    </div>
</div>

我希望看到日期选择器中显示的日期。 但我看到的是“dd/mm/yyyy”占位符。

如果我查看页面源代码,我确实看到该页面确实从我们的数据库中获取了预期日期。

<input class="form-control text-box single-line" data-val="true" data-val-date="The field Start Date must be a date." data-val-required="The Start Date field is required." id="StartDate" name="StartDate" type="date" value="01/01/2018">

我不确定我是否遗漏了什么。

【问题讨论】:

    标签: c# asp.net-mvc data-annotations


    【解决方案1】:

    用日期格式进一步测试后,我没想到浏览器会期望日期值是"yyyy-MM-dd"的形式。

    DataFormatString 值从我当前使用的格式更改为"yyyy-MM-dd" 后,日期选择器能够显示正确的日期。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-09
      相关资源
      最近更新 更多