I use EntityFramework CodeFirst MVC3. In my model I defined a nullable property like this:
public class PostFullViewModel
{
public int PostID { get; set; }
...
public DateTime? PublishDate { get; set; }
...
}
Here is my Create action controller:
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);
}
In my create view:
@model PostCreateViewModel
@using (Html.BeginForm())
{
@Html.LabelFor(model => model.PostToCreate.PublishDate)
@Html.EditorFor(model => model.PostToCreate.PublishDate)
...
}
I got an error on the EditorFor line:
The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'.
How can I proceed to have my creation view showing the PublishDate empty?
Thanks.
I guess you defined a custom editor template for the DateTime type (
~/Views/Shared/EditorTemplates/DateTime.cshtmlor~/Views/XXX/EditorTemplates/DateTime.cshtmlwhereXXXis your current controller name) which is strongly typed toDateTimeinstead ofDateTime?like this:So you could change its type to
DateTime?.