ASP.NET MVC显示日期没有时间

问题描述 投票:10回答:6

我的模型字段以下列方式装饰:

[DataType(DataType.Date)]
[Display(Name = "Date of birth")]
public string DateOfBirth { get; set; }

当我想使用以下代码在视图中显示值时:

<%: Html.DisplayFor(m => m.DateOfBirth) %>

问题是日期与其时间值一起显示。我想知道为什么它不考虑DateType属性并且只显示没有时间的日期值。我知道我可以为DateTime创建一个显示模板,但在其他情况下,除了出生日期,我想与日期一起显示时间。如何解决问题?

c# asp.net-mvc datetime attributes data-annotations
6个回答
4
投票

使用DisplayFormatAttribute指示显示值时的格式。此外,您可以创建两个DisplayTemplates,Date和DateTime,并使用UIHintAttribute指定模板


11
投票

你在这里遇到的问题是你使用的是字符串值而不是DateTime。

将您的模型更改为:

[DataType(DataType.Date)]
[Display(Name = "Date of birth")]
public DateTime? DateOfBirth { get; set; }

DataType仅在它是DateTime类型时才有效,您还可以获得额外的优势,即在使用DateTime时它会自动将其验证为有效日期。如果使用字符串,则必须使用正则表达式验证程序以确保输入正确的日期。


9
投票

这应该用于编辑模式和显示

 [DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:MM/dd/yyyy}")]

虽然如果它只是显示,这可能会奏效

[DisplayFormat(DataFormatString = "{0:d}")]

4
投票

您可以使用ToShortDateString()或ToLongDateString()来仅显示日期,例如:

@Model.EventDate.ToShortDateString()
@Model.EventDate.ToLongDateString()

2
投票

如果您的日期类型为DateTime,并且ToShortDateString()ToLongDateString()仍然不起作用,请检查您的DateTime是否可为空(DateTime?)。使它不可为空可以做到这一点。


0
投票

使用@Value和ToShortDateString(),您只能显示日期。

@Html.TextBoxFor(model => model.StartDate, "", new { id = "date", @class = "datepicker", @style = "width:70%; height:30px;", @placeholder = "Enter Date", @Value = @Model.StartDate.ToShortDateString()})
© www.soinside.com 2019 - 2024. All rights reserved.