asp.net-mvc 在强类型视图中格式化可为空的 DateTime 字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3684015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 00:28:26  来源:igfitidea点击:

Formatting nullable DateTime fields in strong typed View

asp.net-mvcasp.net-mvc-2defaultmodelbinder

提问by Lorenzo

I have a Person class with a BornDate property in my model defined as

我的模型中有一个具有 BornDate 属性的 Person 类定义为

[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

问题是,当我使用 BornDate 文本框编辑 Person 实例时,其格式为

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.

而我想在没有时间部分的情况下对其进行格式化(“dd/MM/yyyy”)。我无法将 toString 方法与格式字符串一起使用,因为它是一个可为空的字段。

what can I do?

我能做什么?

回答by James Hull

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

您应该能够使用 Value。首先检查它是否为空。

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

回答by davidferguson

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.

我知道这已经很晚了,但我正在研究另一个问题并遇到了这个问题。有一种方法可以只显示不需要表示层格式的日期部分。

[DisplayName("Born Date")]
[DataType(DataType.Date)]
public DateTime? BornDate { get; set; }

Using this will ensure that everywhere you bind to this property on your View, only the date will show

使用这将确保您在视图上绑定到此属性的任何地方,只会显示日期

Hope this helps somebody

希望这可以帮助某人

回答by brad oyler

To do this in your VIEW, you can use Razor syntax, as well:

要在您的 VIEW 中执行此操作,您也可以使用 Razor 语法:

 @Html.TextBox("BornDate", item.BornDate.HasValue ? item.BornDate.Value.ToShortDateString():"") 

回答by Shazwazza

You can do this, it will work with Nullable model types:

您可以这样做,它将适用于 Nullable 模型类型:

@model DateTime?
@{
    object txtVal = "";
    if (Model.HasValue) 
    {
        txtVal = Model.Value;
    };
}
@Html.TextBoxFor(x => Model, new {Value = string.Format(ViewData.ModelMetadata.EditFormatString, txtVal))

回答by Brave Programmer

Another way I've tackled this issue is by adding format to the TextBoxFor

我解决这个问题的另一种方法是向 TextBoxFor 添加格式

@Html.TextBoxFor(model => model.BornDate, "{0:MM/dd/yyyy}", new { id = "bornDate" })