开发者

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开发者_如何学Python>
@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


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?>


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

should be

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


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


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>
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜