javascript - EditorTemplate 中的 Bootstrap 3 DateTimePicker
问题描述
创建了一个编辑器模板来动态创建时隙。现在我无法使用 datetimepicker 选择时间。代码如下。以下代码在主视图之外时有效。是否可以在编辑器模板中使用 datetimepicker?
@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", @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", @style = "width: 100px" } })
@Html.ValidationMessageFor(model => model.EndTime, "", new { @class = "text-danger" })
</div>
</div>
@section Scripts
{
<script type="text/javascript">
$(function () {
$('#StartTime').datetimepicker({
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15,
});
});
$(function () {
$('#EndTime').datetimepicker({
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15
});
});
$('#StartTime').removeAttr("data-val-date");
$('#EndTime').removeAttr("data-val-date");
</script>
解决方案
部分不支持部分,并且您的脚本永远不会包含在返回给客户端的 html 中。在任何情况下,脚本都不应该是部分的(这就是 an 的样子EditorTemplate
)——您正在生成内联脚本,这使得调试变得更加困难,并且包含多个脚本实例的风险。
@section Scripts{ ... }
从您的代码中删除代码EditorTemplate
并将其移动到主视图或其布局。为了使这更灵活一点,我建议您给输入一个类名,并将其用作 jQuery 选择器,而不是引用每个个体id
(因此只需要一个脚本)。
此外,在使用方法value
时,您不应该设置属性。HtmlHelper
这些方法正确地生成value
from ModelState
,ViewData
最后按顺序生成模型属性,并且通过设置value
属性,您正在搞砸模型绑定。相反,在将模型传递给视图之前,在 GET 方法中设置值。
您生成日期选择器的代码应该只是
@Html.EditorFor(m => m.StartTime, new { htmlAttributes = new { @class = "form-control datetimepicker" } })
或更简单地说
@Html.TextBoxFor(m => m.StartTime, new { @class = "form-control datetimepicker" })
然后你可以设置宽度
.datetimepicker {
width: 100px;
}
并且视图或布局中的脚本将只是
$('.datetimepicker').datetimepicker({
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15,
});
也不清楚您为什么要尝试使用 删除客户端验证.removeAttr("data-val-date")
,这样做表明您的设计存在问题。您似乎也只想选择一个时间,在这种情况下,您的属性应该是TimeSpan
。
推荐阅读
- mysql - IN 子句挂起 PHPmyadmin - Mysql
- c# - 如何在 Windows 10 IoT 上获取文档文件夹路径。UWP 应用程序
- vb.net - Crystal Report 找不到指定的路径文件
- c++ - 结合两种方法,用write解密android assets
- vba - VBA宏将数据从一个表覆盖到另一个表
- laravel - 仅为 JWT 授权用户访问图像 - Laravel 5.6
- css - 为什么浏览器开发工具中计算的字体大小与我的样式表值不同?
- c# - 组合框和列表框之间的 C# WPF 绑定
- rebol - 等效于红色中的 Rebol 效果 [渐变]?
- vba - 无法定义获取第一个空白单元格的范围