amchoni
amchoni

Reputation: 607

jQuery Datetime picker MVC3

I have 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 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 new Item I have this error message

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

I try

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

But i not have in Model Value check

Upvotes: 7

Views: 10539

Answers (4)

Nenad Dzeverdanovic
Nenad Dzeverdanovic

Reputation: 1

This is the code of my editor template: The point 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>

Upvotes: 0

Ram
Ram

Reputation: 11

Just put ? in your System.DateTime

example :

@model System.DateTime?

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

if you ommit the question mark you will ge an error

Upvotes: 1

B Z
B Z

Reputation: 9453

@inherits System.Web.Mvc.WebViewPage<System.DateTime> 

should be

@inherits System.Web.Mvc.WebViewPage<System.DateTime?>

Upvotes: 2

Max Toro
Max Toro

Reputation: 28608

Try one of the following:

  • If the action is for creating a new object pass a new instance as model, e.g. return View(new MyObject())
  • Change @inherits System.Web.Mvc.WebViewPage<System.DateTime> to @inherits System.Web.Mvc.WebViewPage<System.DateTime?>

Upvotes: 6

Related Questions