JQuery datetime picker MVC3

In my model this field

[DataType(DataType.DateTime)] [Required(ErrorMessage = "Expire is required")] public DateTime Expire { get; set; } 

In my view

 @Html.EditorFor(model => model.Expire)) @Html.ValidationMessageFor(model => model.Expire) 

and I create a DataTime EditorTemplates

 @inherits System.Web.Mvc.WebViewPage<System.DateTime> @Html.TextBox("", (Model.ToShortDateString()), new { @class = "datePicker" }) <script type='text/javascript'> $(document).ready(function () { $(".datePicker").datepicker({ // buttonImage: "/content/images/calendar.gif", // showOn: "both", // defaultDate: $("#calendar-inline").attr('rel') showAnim: 'slideDown', dateFormat: 'dd/mm/yyyy' }); }); </script> 

when i try to create a new item. I have this error message

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

I'm trying to

 Model.HasValue ? Model.Value.ToString("MM/dd/yyyy") : DateTime.Today.ToShortDateString() 

But I do not have a model value in the check

+7
source share
4 answers

Try one of the following:

  • If the action is intended to create a new object, pass the new instance as a model, for example. return View(new MyObject())
  • Change @inherits System.Web.Mvc.WebViewPage<System.DateTime> to @inherits System.Web.Mvc.WebViewPage<System.DateTime?>
+6
source
 @inherits System.Web.Mvc.WebViewPage<System.DateTime> 

it should be

 @inherits System.Web.Mvc.WebViewPage<System.DateTime?> 
+2
source

Just put it down? in your System.DateTime

example:

 @model System.DateTime? @Html.TextBox("", ViewData.TemplateInfo.FormattedModelValue, new { data_datepicker = true }) 

if you omit the question mark you get an error

+1
source

This is the code for my editor template. The goal is to avoid null values:

 @model DateTime? <script src="../../../Scripts/jquery-1.4.4.js" type="text/javascript"></script> <script src="../../../Scripts/jquery-ui.js" type="text/javascript"></script> @Html.TextBox("", (Model.HasValue ? Model.Value.ToShortDateString() : String.Empty), new { @class = "datePicker" }) <script type='text/javascript'> $(document).ready(function () { $(".datePicker").datepicker({ // buttonImage: "/content/images/calendar.gif", // showOn: "both", // defaultDate: $("#calendar-inline").attr('rel') showAnim: 'slideDown', dateFormat: 'dd/mm/yyyy' }); }); </script> 
0
source

All Articles