Nullable DateTime, EditorTemplates, JQ UI DatePicker
My intent was to apply the JQuery UI Datepicker to my entire site by creating an EditorTemplate as per this post ASP.NET MVC 2 Templates
@model DateTime
@{
string name = ViewData.Tem开发者_StackOverflow中文版plateInfo.HtmlFieldPrefix;
string id = name.Replace(".", "-");
<div class="editor-label">
@Html.LabelFor(model => model)
</div>
<div class="editor-field, datepicker">
@Html.EditorFor(model => model)
@Html.ValidationMessageFor(model => model)
</div>
}
The associated code works perfectly as described; however, in addition to several DateTime fields, the Model also contains 1 nullable DateTime field and navigating to the page results in this error:
The model item passed into the dictionary is null, but this dictionary requires a non-null model item of type 'System.DateTime'.
In fact, even creating an empty partial named "DateTime" in the path Views/Shared/EditorTemplates is enough to generate the error, suggesting that even if the template were rewritten it may still not handle a null value. The code in the Index View (generated via MvcScaffolding via EF Code-First) is the same for both nullable and non-nullable DateTime fields:
<div class="editor-label">
@Html.LabelFor(model => model.ItemInstance.iArrivalDate)
</div>
<div class="editor-field,datepicker">
@Html.EditorFor(model => model.ItemInstance.iArrivalDate)
@Html.ValidationMessageFor(model => model.ItemInstance.iArrivalDate)
</div>
So is it possible to modify the template to handle the nullable DateTime?
You specified a model of DateTime which is a value type and cannot be null. That's what the error message is telling you. Try changing your model to be a nullable DateTime.
@model DateTime?
@{...}
That should fix it.
Phil is right (null model) I have a full tutorial on this http://www.asp.net/mvc/tutorials/using-the-html5-and-jquery-ui-datepicker-popup-calendar-with-aspnet-mvc-part-1
精彩评论