首页 > 解决方案 > 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>

标签: javascriptasp.net-mvcdatetimepickerbootstrap-datetimepickermvc-editor-templates

解决方案


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

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

此外,在使用方法value时,您不应该设置属性。HtmlHelper这些方法正确地生成valuefrom ModelStateViewData最后按顺序生成模型属性,并且通过设置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


推荐阅读