格式化强类型视图为空的日期时间字段 [英] Formatting nullable DateTime fields in strong typed View

查看:629
本文介绍了格式化强类型视图为空的日期时间字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有定义为

[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>

问题是,当我编辑的BornDate文本框中输入一个Person实例被格式化为

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

而我想没有时间的一部分(DD / MM / YYYY)对其进行格式化。我不能够使用toString方法与格式字符串,因为它是一个可空场。

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.

我该怎么办?

推荐答案

您应该能够使用的价值。只是检查它不是第一个空。

You should be able to use Value. Just check it isn't null first.

var displayDate = model.BornDate.HasValue ? model.BornDate.Value.ToString("yyyy") : "NoDate";

这篇关于格式化强类型视图为空的日期时间字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆