c# - ASP.NET MVC 显示没有时间的日期

标签 c# asp.net-mvc datetime attributes data-annotations

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

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

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

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

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

最佳答案

这里的问题是您使用的是字符串值而不是 DateTime。

将您的模型更改为:

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

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

关于c# - ASP.NET MVC 显示没有时间的日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6593238/

相关文章:

c# - Windows Phone 8.1 中不包含 'RootVisual' 的定义

c# - 基于 .Net Core 中的 appSettings 使用 Cors

C# 如何单击 IList 中的 IWebelement?

c# - 引用标准库后异常不会进入 ExceptionFilter

asp.net-mvc - ASP.NET 身份 : use GeneratePasswordResetToken on Azure website

javascript - 添加分钟并打印

c# - ASP.Net Core Razor 组件 : await vs . 结果

javascript - 以谓词表达式作为参数获取对 api 的请求

python - pd to_datetime 不将 DDMMMYYYY 日期转换为 python 中的日期时间

mysql - 显示每小时的聚合数据