1

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?

asked Mar 27, 2018 at 0:18

1 Answer 1

2

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

answered Mar 27, 2018 at 2:14
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but unfortunately it still is not displayinf the model value. In the browser there is an error message: 'unexpected value'.
I have update my answer... in java script you can read the value from your input and pass it datatimepicker. this should display the date from the model.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.