I'm using Twitter Bootstrap Datepicker https://github.com/eternicode/bootstrap-datepicker within my MVC 5 application. It's hooked up to a textbox within a View called Selector
View Selector
@model STAR.UI.ViewModels.ReportSelectorViewModel
<script>
$(document).ready(function () {
$('.datepicker').datepicker({
autoclose: true,
format: "dd/mm/yyyy",
daysOfWeekDisabled: "5,6"
});
});
</script>
@Html.TextBoxFor(m => m.StartDate, new { @class = "datepicker" })
When the user selects a date it displays in the textbox in a UK date format dd/mm/yyyy. This is correct. The user can then hit a submit button which displays data on another page. Within that page there is a back button which returns the user back to the Selector View where they can select another date. However, I'd also like when the user hits the back button that their current date selection is also passed back into the textbox.
Back Button
@Html.ActionLink("<<< Go Back", "Selector", "Reports", new { startDate = Model.StartDate }, new { @class = "btn btn-outline btn-primary" })
The back button passes the selected StartDate back to the Selector Action within my Controller and I then assign this value to the ViewModel, and the ViewModel is then passed back to the Selector View.
Selector Action (in Controller)
public ActionResult Selector(DateTime? startDate)
{
ReportSelectorViewModel model = new ReportSelectorViewModel();
model.StartDate = startDate;
return View(model);
}
The StartDate property in the ReportSelectorViewModel is of type DateTime?
The problem is that when the date is returned to the textbox, it is in the format of mm/dd/yyyy instead of the UK format I need, which is dd/mm/yyyy.
I've tried putting this code above the StartDate property in the ReportSelectorViewModel, but it doesn't help
[DataType(DataType.Date), DisplayFormat(DataFormatString = "{0:dd/MM/yyyy}", ApplyFormatInEditMode = true)]
public DateTime? StartDate { get; set; }
Can anyone please help with this?
Thanks.
UPDATE
My Html rendered code for the StartDate
<div class="form-group">
<input class="datepicker" data-val="true" data-val-date="The field StartDate must be a date." data-val-required="Please select a Start Date" id="StartDate" name="StartDate" type="text" value="" />
<span class="field-validation-valid" data-valmsg-for="StartDate" data-valmsg-replace="true"></span>
</div>
Folks
This solved my problem, changing the Html.TextBoxFor declaration to this
@Html.TextBoxFor(model => model.StartDate, new { Value = Model.StartDate.HasValue ? Model.StartDate.Value.ToString("dd/MM/yyyy") : string.Empty, @class = "datepicker" })