2013-02-07 68 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