Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DatePicker Editor Template

Below is an EditorTemplate that renders a Bootstrap datetimepicker with EditorFor helpers, the problem I am seeing is with the script section. It works OK for one DateTimePicker per view - but since I am using class selector, whenever I use 2 or more DateTimePickers per view it renders duplicate <script> sections, confusing the DOM as to on which TextBox to invoke the calendar. What am I missing here?

   @model DateTime?
   <div class='input-group date datePicker'>
      <span class="input-group-sm">
         @Html.TextBox("", Model.HasValue ? Model.Value.ToString("d") : String.Empty)
      </span>
   </div>
   <script type="text/javascript">
       $(function() {
       $('.datePicker').datetimepicker({
           pickTime: false
       });
   });
   </script>
like image 235
kermit_xc Avatar asked Jun 11 '26 15:06

kermit_xc


1 Answers

The problem you have as you have correctly deduced is that the script block defined in the editor template will run twice when you have two datepickers included in a view; When it is run twice, the plugin's behaviour is not as expected.

One solution to this would be to target only the datepicker input in the editor template in each script block. For example,

@model DateTime?
<div class='input-group date datePicker'>
   <span class="input-group-sm">
      @Html.TextBox("", Model.HasValue ? Model.Value.ToString("d") : String.Empty)
   </span>
</div>
<script type="text/javascript">
    $(function() {
        // target only the input in this editor template
        $('#@Html.IdForModel()').datetimepicker({
            pickTime: false
        });
    });
</script>
like image 106
Russ Cam Avatar answered Jun 13 '26 05:06

Russ Cam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!