2013-02-07 67 views
0

我想在我的ASP MVC视图中给出一个字段当前日期的默认值,但我无法弄清楚如何在View代码中执行此操作。我需要允许这个字段是可更新的,但是,因为它并不总是最新的日期。有什么建议么?在ASP MVC3中设置'editor-field'值查看

<div class="M-editor-label"> 
     Effective Date 
    </div> 
    <div class="M-editor-field">    
     @Html.EditorFor(model => model.EffectiveDate) 
     @Html.ValidationMessageFor(model => model.EffectiveDate) 
    </div> 

编辑

我试图给这个字段的默认值模型,像这样

private DateTime? effectiveDate = DateTime.Now; 

    public Nullable<System.DateTime> EffectiveDate 
    { 
     get { return DateTime.Now; } 
     set { effectiveDate = value; } 
    } 

但是,get财产给了我以下错误信息:

Monet.Models.AgentTransmission.EffectiveDate.get must declare a body because it is not marked abstract extern or partial

^(Monet is th项目电子名称,AgentTransmission是当前的模型,我在工作,其中EFFECTIVEDATE是属性的名称。)

第二个编辑

每建议在其中一个答案下面我设置构造函数也是如此,但是当渲染视图时,这仍然会在该字段中留下一个空白值。

public AgentTransmission() 
    { 
     EffectiveDate = DateTime.Now; 
    } 

第三编辑

修正上述问题与get,发布什么,我有我的控制器至今的全部。

public AgentTransmission() 
    { 
     EffectiveDate = DateTime.Today; 
     this.AgencyStat1 = new HashSet<AgencyStat>(); 
    } 

    //Have tried with an without this and got the same results 
    private DateTime? effectiveDate = DateTime.Today; 

    public Nullable<System.DateTime> EffectiveDate 
    { 
     get { return effectiveDate; } 
     set { effectiveDate = value; } 
    } 
+0

试图理解......你是说你想默认或重写model.EffectiveDate的值为DateTime.Today? – Peter

+0

我想默认它到今天。 – NealR

+0

(编辑该问题) – NealR

回答

0

我要解决这一点,因为其他的答案都建议,通过像这样

public AgentTransmission() 
{ 
    EffectiveDate = DateTime.Today; 
    this.AgencyStat1 = new HashSet<AgencyStat>(); 
} 

private DateTime? effectiveDate; 

public Nullable<System.DateTime> EffectiveDate 
{ 
    get { return effectiveDate; } 
    set { effectiveDate = value; } 
} 

在构造函数创建一个默认值,在将此代码添加到特定的页面构造函数初始化新对象;

public ActionResult Create() 
    { 
     return View(new AgentTransmission()); 
    } 
0

我会在模型类的构造函数中设置默认值。事情是这样的:

class YourClass { 
    public DateTime EffectiveDate {get;set;} 

    public YourClass() { 
    EffectiveDate = DateTime.Today; 
    } 
} 
+0

认为这将工作,但在视图中什么也没有显示。我已经完成了,并且检查了'locals'窗口,并且当View被渲染时,它看起来仍然具有'null'的值。 – NealR