Why does my bootstrap datepicker calendar not update when getting a value from a model?

Viewed 902

When the view is first pulled up (using a new, empty model) the datepicker works great. When I pull values to my form from a model, the text in the input box looks fine, but when the calendar opens the date is completely wrong. How can this be fixed?

Controller

public IActionResult Daily(Daily? daily)
{
    new ReportDaily().GetAvailableSavedCriteria(out List<ReportCriteria> reportCriteria, out Notification not);

    if (daily.SelectedCriteria == null) {
        //Create daily report object and initialize the default values
        var newModel = new Daily
        {
            PaymentTypes = DGetPaymentTypes(),
            Users = DGetUsers(),
            Criteria = reportCriteria,
            StartDate = DateTime.Today.Date,
            EndDate = DateTime.Today.Date,
            County = true,
            Municipality = true
        };
        return View(newModel);
    }
    else
    {
        daily.PaymentTypes = HttpContext.Session.GetString("PaymentTypes") == null ? DGetPaymentTypes() : JsonConvert.DeserializeObject<List<Daily.PaymentType>>(HttpContext.Session.GetString("PaymentTypes"));
        daily.Users = HttpContext.Session.GetString("Users") == null ? DGetUsers() : JsonConvert.DeserializeObject<List<Daily.User>>(HttpContext.Session.GetString("Users"));
        daily.Criteria = reportCriteria;
        return View("Daily", daily);
    }
}

View

<div class="row col-12 formdatepicker">
    <input asp-for="StartDate" type="text" class="form-control" id="startdatepicker" />
    <span style="margin-left: 8px; margin-right: 8px; padding-top: 5px;">to</span>
    <input asp-for="EndDate" type="text" class="form-control" id="enddatepicker" />
</div>

JavaScript

$("#startdatepicker").datepicker();
$("#enddatepicker").datepicker();

The value in the textbox is set to 03/10/2020 initially. After clicking in the textbox, the calendar is brought up with the selected date being the current day (in this case 03/25/2020) and when clicking out of the calendar without selecting the date, it gets set anyways. I would like the bootstrap datepicker calendar to be the same value as the textbox. Here is a GIF to illustrate the problem:

Calendar error

1 Answers

That's expected from Datepicker, to set default value to today. If your script is on .cshtml page, you can simply do this:

$("#startdatepicker").datepicker("setDate", new Date('@Model.StartDate'));
$("#enddatepicker").datepicker("setDate", new Date('@Model.EndDate'));

If it's on a separated file, bind your dates to some data- fields or use <input value="@Model.StartDate" hidden="hidden" type="text"> then get them back by Jquery.

Related