DatePicker Editor Template

半城伤御伤魂 提交于 2019-12-03 17:09:53

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>

As far as rendering the script once, what about the following? It works for me so far. Any potential issues?

Editor Template - DateTime.cshtml

@model System.DateTime?
@Html.TextBox("", String.Format("{0:d}", Model.HasValue ? Model.Value.ToShortDateString() : string.Empty), new { @class = "datepicker" })


_Layout.cshtml

<script type="text/javascript">
  $().ready(function () {
    $('.datepicker').datepicker({
      changeMonth: true,
      changeYear: true,
      showOn: "button",
      buttonImage: "/Images/calendar.gif",
      buttonImageOnly: true
    });
   }
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!