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

WebサイトのUIにフィールドを追加できます。そして、そこにカスタム日付を設定します。そして、このフィールドをコンストラクターとパラメーターに追加するだけです。リクエストで日付を適切に送信する方法を知りたくない場合は、日付を文字列として送信し、それを次の方法でDateTimeに変換できます。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;
    }

}

上記のコンストラクターでcustomDateを設定すると、post datetimeとして設定され、noの場合、現在の日時が設定されます。

于 2012-11-27T06:56:37.783 に答える