0

我正在尝试学习 ASP.NET MVC 4,所以我正在尝试制作一个博客来帮助我学习。我似乎无法设置发布时的日期时间,它只是使用当前时间。

这是我的博客模型的代码

public class BlogPost
{
    public int ID { get; set; }
    public string Title { get; set; }
    [DataType(DataType.MultilineText)]
    public string Content { get; set; }
    public DateTime DateTimePosted { get; set; }
    public string Author { get; set; }
    public List<Comment> Comments { get; set; }

    public BlogPost()
    { }

    public BlogPost(int id, string title, string content, string author)
    {
        this.ID = id;
        this.Title = title;
        this.Content = content;
        this.DateTimePosted = DateTime.Now;
        this.Author = author;
    }

}

public class BlogPostDBContext : DbContext
{
    public BlogPostDBContext()
        : base("DefaultConnection")
    { }

    public DbSet<BlogPost> BlogPosts { get; set; }
}

如何更改它以存储发布日期时间?

4

1 回答 1

1

您可以在网站上的 UI 中添加其他字段。并在那里设置自定义日期。只需将此字段添加到您的构造函数和参数中。如果您不想学习如何在请求中正确发送日期,您可以将日期作为字符串发送,然后将其转换为 DateTimeConvert.ToDateTime(customDateString)

public class BlogPost
{
    public int ID { get; set; }
    public string Title { get; set; }
    [DataType(DataType.MultilineText)]
    public string Content { get; set; }
    public DateTime DateTimePosted { get; set; }
    public string Author { get; set; }
    public List<Comment> Comments { get; set; }
    public DateTime? CustomDate { get; set; }

    public BlogPost()
    { }

    public BlogPost(int id, string title, string content, string author, DateTime? customDate)
    {
        this.ID = id;
        this.Title = title;
        this.Content = content;
        this.DateTimePosted = customDate ?? DateTime.Now;
        this.Author = author;
    }

}

在上面的构造函数中,如果您设置 customDate 它将被设置为 post datetime,如果没有,将设置当前 datetime。

于 2012-11-27T06:56:37.783 回答