我在从模型中获取DateTime对象以使其显示在日期时间选择器中时遇到问题。最初,我使用DisplayFormat DataAnnotation将其视为具有特定格式的文本。
我已经尝试添加DataType DataAnnotation。我尝试添加必需的DataAnnotation我尝试将DisplayFormat更改为dd / MM / yyyy。
我见过datatype.date annotation not showing calendar in firefox,并已使用最新版本的Chrome和Firefox进行测试。
原始帐单.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; }
Edit.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">
我不确定是否缺少其他内容。
在对日期格式进行了进一步测试之后,我没想到浏览器期望日期值的格式为"yyyy-MM-dd"
。
将DataFormatString
的值从我当前使用的格式更改为"yyyy-MM-dd"
之后,日期选择器能够显示正确的日期。