2012-01-26 23 views
1

我使用EntityFramework CodeFirst MVC3。在我的模型我定義了一個可爲空的屬性是這樣的:我的模型的可空屬性顯示在我的創建視圖

public class PostFullViewModel 
{ 
    public int PostID { get; set; } 
    ... 
    public DateTime? PublishDate { get; set; } 
    ... 
} 

這裏是我創建動作控制器:

public ActionResult Create() 
    { 
     PostCreateViewModel viewModel = new PostCreateViewModel 
     { 
      PostToCreate = new PostFullViewModel(), 
      Authors = m_AccountBusiness.GetAllUsers().Select(x => new SelectListItem { Text = x.UserName, Value = x.UserID.ToString() }) 
     }; 

     return View(viewModel); 
    } 

在我創建視圖:

@model PostCreateViewModel 

@using (Html.BeginForm()) 
{ 
    @Html.LabelFor(model => model.PostToCreate.PublishDate) 
    @Html.EditorFor(model => model.PostToCreate.PublishDate) 
    ... 
} 

我就得到了一個錯誤EditorFor line:

The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'. 

如何讓我的創作視圖顯示PublishDate爲空?

謝謝。

+0

其中從PostToCreate財產?你能詳細說明嗎? – Ray

+0

我更新了我的問題以顯示創建操作控制器。 – Bronzato

回答

2

我猜你定義它是強類型到DateTime而不是DateTime?喜歡本作的DateTime類型(~/Views/Shared/EditorTemplates/DateTime.cshtml~/Views/XXX/EditorTemplates/DateTime.cshtml其中XXX是你的電流控制器名稱)的自定義編輯模板:

@model DateTime 
... 

,所以你可以將其類型更改爲DateTime?

+0

謝謝。我更新了像你一樣向我展示DateTime?並且在我的編輯器模板的代碼中,我測試Model.HasValue是否顯示在文本框中格式化的日期,或者如果顯示爲空,則顯示空的文本框。 – Bronzato

+0

@Bronzato,如果您只需要使用某種自定義格式來格式化日期,您甚至不需要自定義編輯器模板。您可以用'[DisplayFormat]'屬性簡單地修飾您的'PublishDate'屬性,就像這樣:'[DisplayFormat(NullDisplayText =「」,DataFormatString =「{0:dd/MM/yyyy}」,ApplyFormatInEditMode = true)]公共DateTime? PublishDate {get;組; }'。 –

0

我想無論是作爲達林,BTW,當我假設如下PostCreateViewModel類,我沒有任何問題,在創建視圖

public class PostCreateViewModel 
    { 
     public PostFullViewModel PostToCreate { get; set; } 

    } 
相關問題