Reputation: 2673
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.
Upvotes: 0
Views: 1809
Reputation: 1899
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"
});
});
Upvotes: 1