MVC3 Default value for a DateTime property

本秂侑毒 提交于 2019-12-22 17:06:12

问题


I have a DateTime property on one of my Model classes and want to set it's default vaule to Now. The below code is what I had hoped would work but won't compile. It doesn't like the System.DateTime.Now call:

    [DisplayFormat(DataFormatString = "{0:d}", ApplyFormatInEditMode = true)]
    [Display(Name = "To Date")]
    [Required(ErrorMessage = "To Date is required.")]
    [DefaultValue(System.DateTime.Now)]
    public DateTime DateTo { get; set; }

Any ideas?


回答1:


In the model class:

private DateTime _date = DateTime.Now;
public DateTime Date 
{
  get { return _date; }
  set { _date = value; }
}



回答2:


In C# 6 or higher you can set a default value to an auto property.

public DateTime Date { get; set; } = DateTime.Now;

This is logically the same as the below code, use this for older version of C#, just shorter way of writing.

private DateTime _date = DateTime.Now;
public DateTime Date
{
    get { return _date; }
    set { _date = value; }
}

The above two ways will always return the current date & time. It will set the time when the object is constructed and always return that time there after. To always return the current latest date & time use a get property.

public DateTime Date
{
    get { return DateTime.Now; }
}



回答3:


ctor()
{
   DateTo = DateTime.Now;
}

But beware, when returning View() that expects your object as model. You should always pass the objcet like View(new MyObject()), otherwise constructor won't be invoked and you won't get default value on DateTo.

Your code does not compile because Attributes need compile-time constants as parameters. DateTime.Now is not constant, so compiler complies.




回答4:


You are not able to set DefaultValue to DateTime.Now because DateTime.Now is a method, I suggest you change the default constructor to set DateTo = DateTime.Now it will have the same effect.



来源:https://stackoverflow.com/questions/7891584/mvc3-default-value-for-a-datetime-property

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!