在EditorTemplate中使用Bootstrap 3 DateTimePicker遇时间选择问题求助
当然可以在EditorTemplate中使用datetimepicker!
你遇到的问题大概率是元素ID变化或者脚本加载时机/选择器匹配导致的——毕竟当使用EditorTemplate渲染时,ASP.NET会根据上下文自动生成带前缀的元素ID(比如在循环或嵌套场景下,ID会变成TimeSlots_0__StartTime这种格式),原来的固定#StartTime选择器就找不到目标元素了。
下面是具体的解决思路和修改方案:
核心问题分析
- 主视图中元素ID是固定的
StartTime/EndTime,但EditorTemplate渲染时,ASP.NET会为元素添加父模型前缀,导致ID改变,固定ID选择器失效。 - 直接操作固定ID的脚本,无法适配模板复用的场景。
解决方案:用类选择器替代固定ID选择器
这种方式更灵活,不管模板被渲染多少次,只要类名一致就能匹配到元素。
步骤1:修改EditorTemplate代码,添加统一类名
在你的TimeSlot.cshtml模板中,给时间输入框添加timepicker类:
@model Testing.Models.TimeSlot <div class="form-group row"> @Html.LabelFor(model => model.StartTime, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-2"> @Html.EditorFor(model => model.StartTime, new { htmlAttributes = new { @Value = DateTime.Now.ToString("hh:mm tt"), @class = "form-control timepicker", <!-- 添加timepicker类 --> @style = "width: 100px" } }) @Html.ValidationMessageFor(model => model.StartTime, "", new { @class = "text-danger" }) </div> @Html.LabelFor(model => model.EndTime, htmlAttributes: new { @class = "control-label col-md-2" }) <div class="col-md-2"> @Html.EditorFor(model => model.EndTime, new { htmlAttributes = new { @Value = DateTime.Now.AddMinutes(15).ToString("hh:mm tt"), @class = "form-control timepicker", <!-- 添加timepicker类 --> @style = "width: 100px" } }) @Html.ValidationMessageFor(model => model.EndTime, "", new { @class = "text-danger" }) </div> </div>
步骤2:修改脚本,使用类选择器初始化datetimepicker
把原来的固定ID选择器改成类选择器,同时确保脚本在DOM完全加载后执行:
@section Scripts { <script type="text/javascript"> $(document).ready(function () { // 初始化所有带timepicker类的输入框 $('.timepicker').datetimepicker({ format: 'LT', showClose: true, showClear: true, toolbarPlacement: 'top', stepping: 15 }); // 批量移除日期验证属性 $('.timepicker').removeAttr("data-val-date"); }); </script> }
额外注意事项
- 确保jQuery和datetimepicker的核心脚本已经在主布局(比如
_Layout.cshtml)中正确加载,EditorTemplate不需要重复引用这些脚本。 - 如果是在循环中使用EditorTemplate(比如
@Html.EditorFor(m => m.TimeSlots)),类选择器会自动匹配所有生成的时间输入框,完美适配批量场景。 - 永远不要依赖固定ID来选择模板中的元素——ASP.NET的模板引擎会根据上下文动态修改ID,类选择器或属性选择器才是更可靠的方案。
内容的提问来源于stack exchange,提问作者Demetrick Norris
相关产品推荐
相关产品推荐

