Getting date time always null back to controller in MVC3

岁酱吖の 提交于 2019-12-11 17:27:34

问题


Using MVC3 and jQuery plugin datepicker.

I can see calender and I am able to set the date to the field. But when I post model back to controller, I am always getting null value for the property. And it is displaying that particular date as a not valid date.

This is my model.

[DataType(DataType.DateTime)]
        [DisplayName("PostTime")]
        [DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
        public DateTime? PostTime { get; set; }

And part of my view

    @using (Html.BeginForm())
{
    @Html.ValidationSummary(true)

    <fieldset>
    <legend>BlogPost</legend>

    <div class="editor-label">
    @Html.LabelFor(model => model.PostTitle)
    </div>
    <div class="editor-field">
    @Html.EditorFor(model => model.PostTitle)
    @Html.ValidationMessageFor(model => model.PostTitle)
    </div>

    <div class="editor-label">
    @Html.LabelFor(model => model.PostTime)
    </div>
    <div class="editor-field">
    <span class="datepicker">
    @Html.EditorFor(model => model.PostTime)
    @Html.ValidationMessageFor(model => model.PostTime)
    </span>
    </div>


    <p>
    <input type="submit" value="Create" />
    </p>
    </fieldset>
}

    <script src="http://code.jquery.com/jquery-1.8.2.js"></script>
        <script src="http://code.jquery.com/ui/1.9.1/jquery-ui.js"></script>
        <script type="text/javascript">
            $(document).ready(function () {
                $("#PostTime").datepicker({
                    showOn: 'both',
                    buttonImage: "/content/img/calendar_icon.png"
                });
            });
        </script>

Controller is

[HttpPost]
public ActionResult Create(BlogPost blogpost)
{
    if (ModelState.IsValid)
    {
        var db = new BlogPostContext();
        db.Add(blogpost);
        return RedirectToAction("Index");
    }
    return View(blogpost);
}

Can somebody what I am missing.

Thanks.


回答1:


As far as getting an error saying it isn't a valid date, you'll need to specify the format of the datepicker:

        $(document).ready(function () {
            $("#PostTime").datepicker({
                showOn: 'both',
                dateFormat: 'dd/mm/yy',
                buttonImage: "/content/img/calendar_icon.png"
            });
        });


来源:https://stackoverflow.com/questions/13390622/getting-date-time-always-null-back-to-controller-in-mvc3

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!