简体   繁体   English

ASP.NET MVC 4-设置发布日期时间?

[英]ASP.NET MVC 4 - Set datetime when posted?

I'm trying to learn ASP.NET MVC 4, so I'm trying to make a blog to help me learn. 我正在尝试学习ASP.NET MVC 4,因此我试图创建一个博客来帮助我学习。 I can't seem to set the datetime when it was posted, it just uses the current time. 我似乎无法设置发布的日期时间,它仅使用当前时间。

This is the code I have for my blog model 这是我的博客模型的代码

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; }
}

How can I change this to store the datetime when it was posted? 如何更改此日期以存储发布日期?

You can add additional field to your UI on a website. 您可以在网站的UI中添加其他字段。 And set custom date there. 并在那里设置自定义日期。 And just add this field to your constructor and parameters. 只需将此字段添加到构造函数和参数中即可。 If you don't want to learn how to properly send dates in requests, you could send a date as a string and then convert it to DateTime by Convert.ToDateTime(customDateString) 如果您不想学习如何在请求中正确发送日期,则可以将日期作为字符串发送,然后通过Convert.ToDateTime(customDateString)将其转换为DateTime。

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;
    }

}

In the constructor above if you set customDate it will be set as post datetime, if no, the current datetime will be set. 在上面的构造函数中,如果您设置customDate,它将被设置为post datetime,如果没有,则将设置当前datetime。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM