[英]How do I show the DateTime in the view using the DataType.Date data annotation?
我在從我的 model 獲取 DateTime object 以顯示在日期時間選擇器中時遇到問題。 最初,我使用 DisplayFormat DataAnnotation 將其視為具有特定格式的文本。
我嘗試添加 DataType DataAnnotation。 我已嘗試添加所需的 DataAnnotation 我已嘗試將 DisplayFormat 更改為 dd/MM/yyyy。
我在 firefox 中看到 datatype.date 注釋未顯示日歷,並已使用最新版本的 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; }
編輯.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"
后,日期選擇器能夠顯示正確的日期。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.