EditorTemplate中的Bootstrap 3 DateTimePicker

时间:2018-05-25 15:56:59

标签: 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 = "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>

1 个答案:

答案 0 :(得分:2)

部分中不支持节,并且您的脚本永远不会包含在返回给客户端的html中。在任何情况下,脚本都不应该是部分的(这就是EditorTemplate) - 您正在生成内联脚本,这使得调试更加困难,并且包括多个脚本实例在内的风险。

@section Scripts{ ... }删除EditorTemplate代码,然后将其移至主视图或其布局。为了使其更灵活,我建议您为输入提供类名,并将其用作jQuery选择器,而不是引用每个id(因此只需要一个脚本)。

此外,在使用value方法时,不应设置HtmlHelper属性。这些方法正确地从valueModelState生成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