在强键入视图中格式化无效的DateTime字段
-
02-10-2019 - |
题
我有一个人类的班级,在我的模型中有一个有天生的财产
[DisplayName("Born Date")]
public DateTime? BornDate { get; set; }
我在我的视图中使用这个领域
<td style="white-space:nowrap">
<%= Html.LabelFor(model => model.BornDate)%>
<br />
<%= Html.TextBoxFor(model => model.BornDate, new { id = "bornDate" })%>
<%= Html.ValidationMessageFor(model => model.BornDate, "*")%>
</td>
问题是,当我编辑一个带有born dath born the born文本框的人实例时
dd/MM/yyyy hh.mm.ss
虽然我想在没有时间部分的情况下格式化它(“ DD/mm/yyyy”)。我无法将ToString方法与格式字符串一起使用,因为它是一个可随之而来的字段。
我能做些什么?
解决方案
您应该能够使用价值。只需检查它不是首先。
var displayDate = model.BornDate.HasValue ? model.BornDate.Value.ToString("yyyy") : "NoDate";
其他提示
我知道这已经很晚了,但是我正在研究另一个问题,并遇到了这个问题。有一种方法仅显示不需要演示层格式化的日期部分。
[DisplayName("Born Date")]
[DataType(DataType.Date)]
public DateTime? BornDate { get; set; }
使用此功能将确保您在视图上绑定到此属性的任何地方,只有日期将显示
希望这对某人有帮助
为了在您看来,您也可以使用剃须刀语法:
@Html.TextBox("BornDate", item.BornDate.HasValue ? item.BornDate.Value.ToShortDateString():"")
您可以做到这一点,它将与可无效的模型类型一起使用:
@model DateTime?
@{
object txtVal = "";
if (Model.HasValue)
{
txtVal = Model.Value;
};
}
@Html.TextBoxFor(x => Model, new {Value = string.Format(ViewData.ModelMetadata.EditFormatString, txtVal))
我解决此问题的另一种方法是将格式添加到TextBoxfor
@Html.TextBoxFor(model => model.BornDate, "{0:MM/dd/yyyy}", new { id = "bornDate" })
不隶属于 StackOverflow