简体   繁体   English

RE:MVC5 C#当前日期时间查询

[英]RE: MVC5 C# current datetime query

I'm trying to get my posts to have a preset datetime field but when I go to edit my posts they are set to 01/01/2015 00:00 whereas i'd rather have them be automated to be like 14/07/2015 13:53 (or whatever the current datetime is). 我正在尝试让我的帖子具有预设的datetime字段,但是当我去编辑帖子时,它们设置为01/01/2015 00:00而我希望将它们自动化为14/07/2015 13:53 (或当前日期时间是什么)。 I thought adding a line above my datetime property like [DateTime.current] or something along those lines might work but I've not been successful yet. 我以为在我的datetime属性上方添加一条线,例如[DateTime.current]或沿这些线的内容可能会起作用,但是我还没有成功。

public class Post
{
    public int PostID { get; set; }
    public Guid UserID { get; set; }
    public int ThreadID { get; set; }
    public string PostTitle { get; set; }
    public DateTime PostDateTime { get; set; }
    public string PostBody { get; set; }
}

If this is your model, you could use the default constructor. 如果这是您的模型,则可以使用默认构造函数。

public class Post
{
    public int PostID { get; set; }
    public Guid UserID { get; set; }
    public int ThreadID { get; set; }
    public string PostTitle { get; set; }
    public DateTime PostDateTime { get; set; }
    public string PostBody { get; set; }

    public Post()
    {
       PostDateTime = DateTime.Now;
    }
}

Model binding occurs after the model has been created, so it won't affect MVC. 模型绑定是在创建模型后发生的,因此不会影响MVC。

Why not add a constructor to your Post class and pass the initial value you want your post to be initialized with ? 为什么不向您的Post类添加一个构造函数并传递您希望用其初始化帖子的初始值?

public class Post
{
    public int PostID { get; set; }
    public Guid UserID { get; set; }
    public int ThreadID { get; set; }
    public string PostTitle { get; set; }
    public DateTime PostDateTime { get; set; }
    public string PostBody { get; set; }

    public Post( DateTime initialValue)
    {
         PostDateTime = initialValue;
    }
}

Set the default DateTime that you would like in the constructor 设置您想要在构造函数中的默认DateTime

public class Post
{
    public Post()
    {
        PostDateTime = DateTime.Now;
    }

    public int PostID { get; set; }
    public Guid UserID { get; set; }
    public int ThreadID { get; set; }
    public string PostTitle { get; set; }
    public DateTime PostDateTime { get; set; }
    public string PostBody { get; set; }
}

When this model is bound on the server side from values submitted by the client side, a Post instance will be created with a PostDateTime value as set in the constructor, but then this value will be overridden by the model binding process and set to the value submitted by the client, since PostDateTime is a property with a public setter. 当此模型在服务器端与客户端提交的值绑定在一起时,将使用构造函数中设置的PostDateTime值创建一个Post实例,但是此值将被模型绑定过程覆盖并设置为该值由于PostDateTime是具有公共设置程序的属性,因此由客户端提交。

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

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