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

GUZ*_*GUZ 11 c# asp.net-mvc datetime attributes data-annotations

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

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

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

<%: Html.DisplayFor(m => m.DateOfBirth) %>
Run Code Online (Sandbox Code Playgroud)

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

Eri*_*sch 11

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

将您的模型更改为:

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

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


dov*_*ove 9

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

 [DisplayFormat(ApplyFormatInEditMode = true,DataFormatString = "{0:MM/dd/yyyy}")]
Run Code Online (Sandbox Code Playgroud)

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

[DisplayFormat(DataFormatString = "{0:d}")]
Run Code Online (Sandbox Code Playgroud)


arc*_*hil 6

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


zal*_*exy 5

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

@Model.EventDate.ToShortDateString()
@Model.EventDate.ToLongDateString()
Run Code Online (Sandbox Code Playgroud)