简体   繁体   English

DatePicker编辑器模板

[英]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. 下面是一个EditorTemplate,它使用EditorFor帮助器呈现Bootstrap datetimepicker,我看到的问题是脚本部分。 It works OK for one DateTimePicker per view - but since I am using class selector, whenever I use 2 or more DateTimePicker s per view it renders duplicate <script> sections, confusing the DOM as to on which TextBox to invoke the calendar. 它适用于每个视图的一个DateTimePicker - 但由于我正在使用类选择器,每当我在每个视图中使用2个或更多DateTimePicker ,它会呈现重复的<script>部分,使DOM混淆在哪个TextBox上调用日历。 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>

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. 对此的一个解决方案是仅针对每个脚本块中的编辑器模板中的datepicker输入。 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM