簡體   English   中英

Bootstrap 3 DateTimePicker在EditorTemplate中

[英]Bootstrap 3 DateTimePicker in EditorTemplate

創建了一個編輯器模板以動態創建時隙。 現在,我無法使用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中永遠不會包含您的腳本。 在任何情況下,腳本都不應該是局部的(這就是EditorTemplate的意思)-您正在生成內聯腳本,這使得調試更加困難,並且冒着包含多個腳本實例的風險。

從您的EditorTemplate刪除@section Scripts{ ... }代碼,然后將其移至主視圖或其布局。 為了使其更加靈活,我建議您為輸入提供一個類名,並將其用作jQuery選擇器,而不是引用每個單獨的id (因此只需要一個腳本)。

此外,在使用HtmlHelper方法時,切勿設置value屬性。 這些方法可以正確地從ModelStateViewData以及最終按該順序的模型屬性生成value ,並且通過設置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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM