我有一个包含以下内容的viewmodel:
public class CreateCardviewmodel { [HiddenInput(DisplayValue = false)] public int SetId { get; set; } [required] public IList<Side> Sides { get; set; } [required] public int Stage { get; set; } [required] [DataType(DataType.Date)] [HiddenInput(DisplayValue = false)] public DateTime DateCreated { get; set; } [required] public bool IsReady { get; set; } }
模型如下:
public class Card { public virtual int CardId { get; set; } // belongs to a Set public virtual int SetId { get; set; } public virtual Set Set { get; set; } // has Sides public virtual IList<Side> Sides { get; set; } // is in a certain Stage public virtual int Stage { get; set; } // is ready to study public virtual bool IsReady { get; set; } public virtual DateTime DateCreated { get; set; } }
如何为DateCreated设置默认值?
如果我想在创建卡片时在侧面插入空白边,该方法会改变吗?
解决方法
您可以在构造函数中设置默认值:
public CreateCardviewmodel() { DateCreated = DateTime.Now; Sides = new List<Side> { new Side() }; }
警告:从单元测试角度来看使用DateTime.Now存在问题.如果您正在对viewmodel创建进行单元测试,并且需要能够验证创建的日期是否设置为已知值,则可以查看为时间创建单独的概念,如Ayende’s blog中所述.您基本上创建了一个静态函数,SystemTime,您可以在测试中将其设置为已知值.如果未设置,则默认为DateTime.Now:
public static class SystemTime { public static Func<DateTime> Now = () => DateTime.Now; }
public CreateCardviewmodel() { DateCreated = SystemTime.Now(); Sides = new List<Side> { new Side() }; }
如果您需要将时间实际设置为已知值,请执行以下操作:
SystemTime.Now = () => new DateTime(2013,2,11,17,41,12);