在强类型视图中格式化可为 null 的 DateTime 字段
我的模型中有一个具有 BornDate 属性的 Person 类,定义为
[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>
问题是,当我使用 BornDate 文本框编辑 Person 实例时,其格式设置为,
dd/MM/yyyy hh.mm.ss
而我想将其格式化而不使用时间部分(“dd/MM/yyyy”)。我无法将 toString 方法与格式字符串一起使用,因为它是一个可为空的字段。
我能做些什么?
I have a Person class with a BornDate property in my model defined as
[DisplayName("Born Date")]
public DateTime? BornDate { get; set; }
I use this field in my view as
<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>
The problem is that when I am editing a Person instance with the BornDate text box is formatted as
dd/MM/yyyy hh.mm.ss
while I would like to format it without the time part ("dd/MM/yyyy"). I am not able to use the toString method with the format string because it is a nullable field.
what can I do?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
您应该能够使用价值。首先检查它不为空。
You should be able to use Value. Just check it isn't null first.
我知道这已经很晚了,但我正在研究另一个问题并遇到了这个问题。有一种方法可以只显示日期部分,不需要表示层格式化。
使用此功能将确保您在视图上绑定到此属性的任何地方,只有日期会显示
希望这对某人有帮助
I know this is very late but I was researching another problem and came across this issue. There is a way to only show the date part which does not require presentation layer formatting.
Using this will ensure that everywhere you bind to this property on your View, only the date will show
Hope this helps somebody
要在 VIEW 中执行此操作,您也可以使用 Razor 语法:
To do this in your VIEW, you can use Razor syntax, as well:
您可以这样做,它将适用于 Nullable 模型类型:
You can do this, it will work with Nullable model types:
我解决这个问题的另一种方法是向 TextBoxFor 添加格式
Another way I've tackled this issue is by adding format to the TextBoxFor