2017-03-06 50 views
0

我想正确显示一个(可为空)仅Date-type-only字段。对于这个领域,我的模型和视图模型类被定义为....排除时间从TextBoxFor当ViewModel设置为DataType的日期

[DisplayFormat(DataFormatString = "{0:M/dd/yyyy}")] 
[DataType(DataType.Date)]  
public DateTime? PeriodEnd { get; set; } 

在我的详细信息视图(基于模型),它显示的日期正确(不包括时间因素):

@Html.DisplayNameFor(model => model.PeriodEnd) 

问题:在我的编辑视图中(基于ViewModel),它显示了时间,我试图排除。这是如何定义的。

@Html.TextBoxFor(model => model.PeriodEnd, new { @class = "datepicker" }) 

我也试过....

@Html.TextBoxFor(model => model.PeriodEnd.Value().ToShortDateString(), 
    new { @class = "datepicker" }) 

...但产生的错误。

有没有更好的方法来实现这个目标?

+0

可能相关:http://stackoverflow.com/questions/11179027/asp-net-mvc-3-remove-time-from-date –

回答

2

那么,首先,你没有利用数据注释。像DataType.Date这样的东西本身不会做任何事情。使用编辑器模板(Html.EditorFor),可以使用它来提供date类型的输入,但如果使用Html.TextBoxFor,它基本上被忽略。

您可以通过1)使用Html.EditorFor代替或2)明确设置类型:@Html.TextBoxFor(m => m.PeriodEnd, new { type = "date", @class = "datepicker" })来解决该问题。

+0

谢谢@ChrisPratt。我尝试了两个建议,但是文本框显示了“mm/dd/yyyy”(字面意思)的文本/掩码。 – WebDevGuy2

0

这是解决方案:

@Html.TextBoxFor(m => m.PeriodEnd, "{0:M/d/yyyy}", new { @class = "datepicker" }) 

感谢所有您的反馈!