ASP.NET MVC 5 使用 DateTimePicker (Bootstrap)

2020-08-12

筆記介紹 Bootstrap CSS Framework 下如何使用 DateTimePicker 的各種方式 🌞

logo

實作方式

Html 5 DateTimePicker (Chrome & Edge Support)

  1. 加入 Views/Shared/EditorTemplates
  2. 上述資料夾加入 DateTimePicker.cshtml
@model DateTime?
@{
    var shortDate = DateTime.Parse(Model.ToString()).ToString("yyyy-MM-dd");
}
@Html.TextBoxFor(m => m, new { @class= "form-control", @type="date", @Value= shortDate })
  1. EditorFor 指定使用 Templates
<div class="form-group">
    @Html.LabelFor(model => model.WorkDate, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.EditorFor(model => model.WorkDate, "DateTimePicker")
        @Html.ValidationMessageFor(model => model.WorkDate, "", new { @class = "text-danger" })
    </div>
</div>

如果要同時使用 Date & Time Picker 要使用 datetime-local

@Html.TextBoxFor(model => model.PostDatetimeStart, new { 
    @class = "form-control", 
    @type = "datetime-local", 
    @Value = Model.PostDatetimeStart.Value.ToString("yyyy-MM-ddTHH:mm") })

此外資料的轉換,也可以透過 Model 的 Attribute 來設定:

[DisplayFormat(DataFormatString = "{0:yyyy-MM-ddTHH:mm}", ApplyFormatInEditMode = true)]
public DateTime PostDatetimeStart { get; set; }

jquery.datetimepicker

  1. Nuget install jquery.datetimepicker
  2. bundleConfig.cs 加入 /scripts/jquery.datetimepicker.js
  3. 修正 jquery.datetimepicker.js lang: 'zh-TW'
<div class="form-group">
  <span class="ml-4 badge-info p-1">日期時間選擇器 jquery.datetimepicker</span>
  @Html.LabelFor(model => model.DateTimeCol, htmlAttributes: new { @class =
  "control-label col-md-2" })
  <div class="col-md-10">
    @Html.EditorFor(model => model.DateTimeCol, new { htmlAttributes = new {
    @class = "form-control w-25" } }) @Html.ValidationMessageFor(model =>
    model.DateTimeCol, "", new { @class = "text-danger" })
  </div>
</div>

Tempus Dominus (bootstrap 4)

  1. Nuget install moment.js
  2. Npm install tempusdominus-bootstrap-4
  3. 複製 tempusdominus-bootstrap-4/build 中的 tempusdominus-bootstrap-4.css 及 tempusdominus-bootstrap-4.js
  4. 將複製的檔案加入 Asp.net MVC 專案,分別存於 Content 及 Scripts
  5. bundleConfig.cs 加入
bundles.Add(new ScriptBundle("~/bundles/datetimepicker").Include(
            "~/Scripts/moment.js",
            "~/Scripts/moment-with-locales.js",
            "~/Scripts/tempusdominus-bootstrap-4.js"));
  1. bundleConfig.cs 加入 "~/Content/tempusdominus-bootstrap-4.css"

新增資料端

日期 input 調整為

@Html.EditorFor(
  model => model.WorkDate,
  new
  {
    htmlAttributes = new {
      @class = "form-control datetimepicker-input",
      data_toggle = "datetimepicker",
      data_target ="#WorkDate"
    }
  }
)

View 加入 Scripts

$(function () {
    $('#WorkDate').datetimepicker({
        format: 'L', // Only Date
        locale: 'zh-tw'
    });
});

編輯資料端

Input 不使用 HtmlHelper 改使用 Custom Html Tag

<div class="form-group">
    @Html.LabelFor(model => model.WorkDate, htmlAttributes: new { @class = "control-label col-md-10" })
    <div class="col-md-10">
        <input class="form-control datetimepicker-input text-box single-line"
                data-target="#WorkDate"
                data-toggle="datetimepicker"
                data-val-date="欄位必須是日期。" 
                data-val-required="欄位是必要項。" 
                data-val="true" id="WorkDate"
                name="WorkDate" type="datetime"
                >
        @Html.ValidationMessageFor(model => model.WorkDate, "", new { @class = "text-danger" })
    </div>
</div>

Scripts 代入預設值 (defaultDate)

$('#WorkDate').datetimepicker({
    defaultDate: "@HttpUtility.HtmlEncode(Model.WorkDate).Split(' ').First()",
    format: 'L',
    locale: 'zh-tw',
});

實作結果

tempusdominus 參考

Bootstrap.v3.Datetimepicker (bootstrap 3)

  1. Nuget install Bootstrap.v3.Datetimepicker.CSS
  2. Nuget install Bootstrap.v3.Datetimepicker

待實作

AIR DATEPICKER

Air Datepicker