Search code examples
asp.net-corebootstrap-datetimepickereonasdan-datetimepicker

Bind Bootstrap3 datetimepicker with ASP.NET Core model value


I'm trying to bind the Bootstrap 3 Datetimepicker to to my ASP.NET Core model using the MVC tag helper like this:

<div class='input-group date' id='datetimepicker1'>
    <input asp-for="Observation.ObservationDateTime" type='text' class="form-control" />
    <span class="input-group-addon">
        <span class="glyphicon glyphicon-calendar"></span>
    </span>
</div>

I am hitting a problem initialising the control. The following does not work:

1) in the Razor section scripts like this:

@section Scripts {
    @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}

<script type="text/javascript">
    $(function () {
        $('#datetimepicker1').datetimepicker();
    });
</script>
}

Doing this initialises the datetimepicker, but without the model value. How do I get it to work but with the model value as the initial value?


Solution

  • Include your date field in the view like this:

    @Html.EditorFor(model => model.MyDate, new { htmlAttributes = new { @class = "my-date" } })
    

    And initialize it in your JavaScript like this (I am using jQuery)

    $(document).ready(function () {
        // get date from MyDate input field
        var date = $(".my-date").val();
    
       // use current date as default, if input is empty
       if (!date) {
           date = new Date();
       }
    
        $('.my-date').datetimepicker({
            format: 'YYYY/MM/DD',
            date: date
        });
    });
    

    Please note that I am using 'my-date' class as input selector, you may want to select it differently... and obviously you need to include the the bootstrap library...

    As a side note, it is best practice to put your script in an external file: why should I avoid inline Scripts