7

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

4 Answers 4

6

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?>
Sign up to request clarification or add additional context in comments.

Comments

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

should be

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

Comments

1

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

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.