MVC:ViewModel 值不会显示在使用 type="month" 的日期选择器中

MVC: ViewModel values will not display in datepicker using type="month"

很抱歉,如果有人问过这个问题 - 我已经搜索了 Google 一个小时但没有成功,所以我想我会 post 在这里看看我是否能得到答案。

我正在使用 MVC 5 + Entity Framework 构建 Web 应用程序。我正在开发的模块之一是加油卡跟踪器,其中包含有关附加在车辆上的加油卡的详细信息。

我有一个名为 FuelCardViewModel 的基本视图模型,它是带有几个 SelectList 对象的 FuelCard 模型(来自 EF)。我有一个 属性 是一个 DateTime 属性 叫做 ExpiryDate 它将保存卡的到期日期。

当我填充视图模型并将其发送到 Edit 视图时,所有字段都使用 ViewModel 除了 ExpiryDate 字段。当此字段设置为 type = "date" 时,该值被提取并正确显示,所以我知道这不是我的 ViewModel 绑定的问题。问题是,我只想要 month/year ,所以我必须使用 type = "month"。当它设置为type = "month"(只显示一个month/year picker as per card expiry date formatting)时,该值不显示(尽管我在查看源代码和查看时仍然可以看到该值value 属性。这进一步支持了 ViewModel 绑定工作正常的事实,但在使用月份选择器而不是普通日期选择器时只是格式混乱了)。非常感谢对此的任何帮助;如果需要更多信息,请告诉我,我可以提供。

ExpiryDate 属性 在 FuelCardViewModel:

[Required]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MMMM yyyy}")]
[DataType(DataType.Date)]
[DisplayName("Expiry Date")]
public DateTime ExpiryDate { get; set; }

如果我想使用 type = "date",我必须按照此处的其他答案将 {0:MMMM yyyy} 更改为 {0:yyyy-MM-dd},因此将其更改为 {0:MMMM yyyy} 只是一个尝试解决问题。

我的 Edit 视图中的字段:

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

Edit 视图的显示方式(type = "month"):

View Image

Edit视图应该如何显示:

View Image

终于解决了!我想我会post这里的解决方案来帮助有需要的人。

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:MMMM yyyy}")]

应该是这样的:

[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:yyyy-MM}")]

这么简单的错误,但我的问题现在已经解决了!