user1490835 user1490835 - 3 months ago 13
jQuery Question

jquery dates does not populate model object on post action

i have this razor view:

<div class="panel-body">
<div class="form-group row">
<div class="col-sm-6">
@Html.LabelFor(model => model.DrivingLicenceNo, "Licence No", htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.DrivingLicenceNo, new { htmlAttributes = new { @class = "form-control" } })
</div>

<div class="col-sm-6">
@Html.LabelFor(model => model.DrivingLicenceExpiryDate, "Expiry Date", htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.DrivingLicenceExpiryDate, new { htmlAttributes = new { @class = "form-control" } })
</div>

</div>
<div class="form-group row">
<div class="col-sm-6">
@Html.LabelFor(model => model.DrivingLicenceImage, "Licence Image", htmlAttributes: new { @class = "control-label" })
<input type="file" name="uploadFile" />

</div>
<div class="col-sm-6">
@Html.LabelFor(model => model.DateofBirth, "Date of Birth", htmlAttributes: new { @class = "control-label" })
@Html.EditorFor(model => model.DateofBirth, new { htmlAttributes = new { @class = "form-control" } })
</div>



</div>

</div>


and to display dates, i am using the following script:

<script>
$(function() {
$("#DrivingLicenceExpiryDate").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd-mmm-yyyy'
});
$("#DateofBirth").datepicker({
changeMonth: true,
changeYear: true,
dateFormat: 'dd-mmm-yyyy'
});


});


however without using the script, i get the dates populated in the post action method model but when i put the script back in, the dates in the model object does not get populated. i need to display the drop down menu to make it easier for the user to pick dates

Answer

I am not sure your dateFormat is correct. With the format you specified currently, It will set a date like "25-088-20162016" to the input field. When the form is posted, Model binder will not be able to set this to a DateTime property as the value (or the format of the value) does not looks like a correct date time value.

Try this format.

$(function() {
        $("#DateofBirth").datepicker({
            changeMonth: true,
            changeYear: true,
            dateFormat: 'dd-mm-yy'
        });
 });

Or If you strongly believe that format is a valid date format (for some valid culture), you can set the culture in the server so that server knows how to process the input value coming in.

Adding 2 links for reference

  1. globalization Element

  2. How do you globally set the date format in ASP.NET?

Comments