创建了一个编辑器模板来动态创建时间段。现在我无法使用 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 中。在任何情况下,脚本都不应该是局部的(EditorTemplate
就是这样)- 您正在生成内联脚本,这使得调试变得更加困难,并且存在包含多个脚本实例的风险。
从 EditorTemplate
中删除 @section Scripts{ ... }
代码,并将其移至主视图或其布局。为了使其更加灵活,我建议您为输入提供一个类名,并将其用作 jQuery 选择器,而不是引用每个单独的 id
(因此只需要一个脚本)。
此外,在使用 HtmlHelper
方法时,切勿设置 value
属性。这些方法正确地从 ModelState
、ViewData
和最后的模型属性中生成 value
,并通过设置 value
属性,你搞砸了模型绑定(bind)。相反,在将模型传递给 View 之前,在 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;
}
View 或布局中的脚本将只是
$('.datetimepicker').datetimepicker({
format: 'LT',
showClose: true,
showClear: true,
toolbarPlacement: 'top',
stepping: 15,
});
也不清楚您为什么要尝试使用 .removeAttr("data-val-date")
删除客户端验证,这样做表明您的设计存在问题。似乎您只想选择一个时间,在这种情况下,您的属性应该是 TimeSpan
。
关于javascript - EditorTemplate 中的 Bootstrap 3 DateTimePicker,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50532993/