【问题标题】:Insert datetime [duplicate]插入日期时间 [重复]
【发布时间】:2014-02-20 02:41:08
【问题描述】:
我有一个像这样的 POSTS 的基类
public partial class Post
{
public int Id { get; set; }
public string Title { get; set; }
public DateTime PostDate { get; set; }
public virtual ICollection<Tag> Tag { get; set; }
}
我想让PostDate 在创建记录时始终具有一个值,而不是在表单中指定它。也许你们知道一些好的解决方案,也许有一些注释或什么可以做到这一点?
【问题讨论】:
标签:
asp.net
asp.net-mvc-4
datetime
annotations
【解决方案1】:
在类的构造函数中设置它。创建新实例时会调用它。
public partial class Post
{
public Post()
{
PostDate = DateTime.Now; // or DateTime.UtcNow;
}
public int Id { get; set; }
public string Title { get; set; }
public DateTime PostDate { get; set; }
public virtual ICollection<Tag> Tag { get; set; }
}
【解决方案2】:
就用这个吧:
post.PostDate = DateTime.UtcNow;
在您创建新帖子时添加它。或者,您可以在使用default 创建表时在 sql 中创建。
【解决方案3】:
我认为下面会帮助你
[Required]
[DataType(DataType.Date, ErrorMessage="Your message")]
public DateTime? PostDate { get; set; }