c# - 在模型中设置 DataType.DateTime 的初始值

标签 c# asp.net asp.net-mvc

我正在将模型传递给 View ,模型包含此属性:

[Required(ErrorMessage = "Please enter a start date")]
[DataType(DataType.DateTime)]
[DisplayName("Start Date")]
public DateTime StartDate { get; set; }

我的观点是:

<%: Html.TextBoxFor(m => m.StartDate) %>

当我加载页面时,文本框会填充一个日期:1/1/0001 12:00:00 AM

有没有办法避免这种情况发生,也许是通过使用元数据?

最佳答案

在构造函数中,以编程方式将 StartDate 属性设置为要用作默认日期的日期。 (例如 DateTime.Today。)

如果您希望该值最初为空,请尝试使用 Nullable<DateTime>这将默认为 null。

关于c# - 在模型中设置 DataType.DateTime 的初始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4790096/

相关文章:

c# - 通过使用 C# 指令在 ASP.NET MVC 应用程序中启用 "Debug mode"

c# - 新手 LINQ - 使用 XDocument 读取、过滤 XML

c# - Int 到带前导 0 的字符串转换

c# - 正确处理空值

caching - 在 ASP.NET MVC 中使用 Azure AppFabric 缓存

C# Web API 路由与 Angular 路由混合

c# - FormsAuthentication Membership.GetUser() 空

javascript - 在 Visual Studio 2015 的 UWP 中调试 Javascript

c# - 进入角色受限网页时,ASP.NET 默认页面重定向

c# - IClassFactory 由于以下错误 : 80040154 Class not registered (Exception from HRESULT: 0x80040154 (REGDB_E_CLASSNOTREG)) 而失败