Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC Html.HIddenFor value not being passed to the model

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();
    }
like image 821
Simon Price Avatar asked Oct 20 '22 03:10

Simon Price


2 Answers

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.

like image 107
Rhys Avatar answered Oct 22 '22 00:10

Rhys


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.

like image 31
Linus Caldwell Avatar answered Oct 21 '22 22:10

Linus Caldwell