MVC Html.HIddenFor value not passed to model

I am working with jQueryUI Datepicker and this is the code that I use 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 I click submit \ search available slots, this does not seem to return my selected date back to the model.

This is a model that conveys a date.

 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; } } } 

Could you tell me where I am wrong and what I need to do to fix this.

--------------- edit to show receipt and publication methods ---------------

 // GET: Bookings public ActionResult Index() { return View(); } [HttpPost] public ActionResult Index(AvailableDate availableDate) { return View(); } 
+5
source share
2 answers

Currently, a hidden DateAvailable field DateAvailable always be null. When you click a date from a data collector, it does not currently update the hidden field.

So instead

 $(function () { $("#datepicker").datepicker(); }); 

to try:

 $(function() { $("#datepicker").datepicker({ dateFormat: 'dd-mm-yy', onSelect: function (dateText, e) { $("#DateAvailable").val($(this).val()); } }); }); 

This will give the hidden field a value. In addition, as discussed in our conversion, the date must be formatted as defined above dateFormat: 'dd-mm-yy' .

+2
source

Are you sure the selected date applies to the hidden field? Maybe you should use altField :

 $( "#datepicker" ).datepicker({ altField: ".datepicker" }); 

where .datepicker will be the class you enter for the hidden field. Or it’s better to use your identifier and apply the format:

 $( "#datepicker" ).datepicker({ altField: "#DateAvailable", altFormat: "dd-mm-yy" // added for conversion compatibility }); 

See fiddle .

+1
source

All Articles