kenwarner
kenwarner

Reputation: 29130

Nullable DateTime with Html.EditorFor() ASP.NET MVC helper

I have a DateTime? StartDate { get; set; } in my asp.net mvc viewmodel, and I tried to do Html.EditorFor(x => x.StartDate) in my view. I got an error

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

Anything good way to get around this without creating a non-nullable surrogate property on my viewmodel?

Upvotes: 2

Views: 5127

Answers (2)

archil
archil

Reputation: 39501

Most probably you have defined datetime editor template like this - Views/Shared/EditorTemplates/Datetime.cshtml

@model Datetime
//etc

Change model to take nullable datetime

@model Datetime?
//etc

Upvotes: 4

Philip Fourie
Philip Fourie

Reputation: 117037

This might be the answer to your issue:

<%: Html.EditorFor(model => model.SomeNullableDecimal, "NullableDecimalTemplate" )%>

Credit: ASP.NET MVC 2 - Html.EditorFor a nullable type?

Upvotes: 2

Related Questions