Reputation: 37
I'm trying to learn ASP.NET MVC 4, so I'm trying to make a blog to help me learn. 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?
Upvotes: 0
Views: 1804
Reputation: 836
You can add additional field to your UI on a website. 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)
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.
Upvotes: 1