Javascript EditorTemplate中的Bootstrap 3日期时间选择器
创建了一个编辑器模板以动态创建时间段。现在我无法使用datetimepicker选择时间。代码如下。以下代码在与主视图分离时起作用。是否可以在editortemplate中使用datetimepickerJavascript EditorTemplate中的Bootstrap 3日期时间选择器,javascript,asp.net-mvc,datetimepicker,bootstrap-datetimepicker,mvc-editor-templates,Javascript,Asp.net Mvc,Datetimepicker,Bootstrap Datetimepicker,Mvc Editor Templates,创建了一个编辑器模板以动态创建时间段。现在我无法使用datetimepicker选择时间。代码如下。以下代码在与主视图分离时起作用。是否可以在editortemplate中使用datetimepicker @model Testing.Models.TimeSlot <div class="form-group row"> @Html.LabelFor(model => model.StartTime, htmlAttributes: new { @class = "
@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脚本{…}代码,并将其移动到主视图或其布局。为了使这一点更加灵活,我建议您为输入提供一个类名,并将其用作jQuery选择器,而不是引用每个单独的id,因此只需要一个脚本 此外,在使用HtmlHelper方法时,不应设置value属性。这些方法按照顺序正确地从ModelState、ViewData以及最后的model属性生成值,通过设置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,
});
还不清楚为什么要尝试使用.removeAttrdata val date删除客户端验证,这样做表明您的设计存在问题。您似乎只想选择一个时间,在这种情况下,您的属性应该是TimeSpan。是否有DateTime或DateTime的编辑器模板?类型?如果没有,使用EditorFor可能不会比简单地使用TextBoxFor(他们有DateTime?)更有用。这很有效。谢谢此外,不再使用removeAttr。有一个问题,它需要一个日期和时间,但只是时间。自那以后,这一问题得到了解决。谢谢你多跑了一英里。