I am working with JQueryUI Datepicker, and this is the code I am using in the view
@model myprojectName.WebSite.DataModel.AvailableDate
<script>
$(function () {
$("#datepicker").datepicker();
});
</script>
<h3 class="headerColorWhite">Book a session with Mike</h3>
<p class="mainText">Select a date that you wish to train with Mike</p>
@using (Html.BeginForm())
{
<div class="editor-field left" id="datepicker">
@Html.HiddenFor(model => model.DateAvailable, new {@class = "datepicker"})
@Html.ValidationMessageFor(model => model.DateAvailable)
</div>
<div class="col-md-10 left">
<input type="submit" value="Search Available Slots" class="btn btn-default left" />
</div>
}
When hitting the submit \ search available slots button, this doesn't appear to be sending my selected date back to the model.
This is the Model that its passing the date to
public partial class AvailableDate
{
private DateTime? _DateAvailable;
[DataType(DataType.Date)]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd-MM-yyyy}")]
public System.DateTime DateAvailable
{
get { return _DateAvailable ?? DateTime.Today; }
set { _DateAvailable = value; }
}
}
Can you please let me know where I am going wrong and what I need to do in order to fix this.
--------------- edit to show get and post methods---------------
// GET: Bookings
public ActionResult Index()
{
return View();
}
[HttpPost]
public ActionResult Index(AvailableDate availableDate)
{
return View();
}
At the moment, the hidden field DateAvailable
will always be set to null. When you click a date from the data picker, it isn't currently updating the hidden field.
So, instead of
$(function () {
$("#datepicker").datepicker();
});
try:
$(function() {
$("#datepicker").datepicker({
dateFormat: 'dd-mm-yy',
onSelect: function (dateText, e) {
$("#DateAvailable").val($(this).val());
}
});
});
This will assign the hidden field a value. Also, as discussed in our conversion, the date would need to be formatted, as defined by dateFormat: 'dd-mm-yy'
above.
Are you sure the selected date is applied to the hidden field? Maybe you should use altField
:
$( "#datepicker" ).datepicker({
altField: ".datepicker"
});
where .datepicker
would be the class you inject for the hidden field. Or better use its id and apply a format:
$( "#datepicker" ).datepicker({
altField: "#DateAvailable",
altFormat: "dd-mm-yy" // added for conversion compatibility
});
See this fiddle.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With