ASP.NET MVC 5 使用 Bootstrap4 設計表單 (Design Forms With BS4)


  1. ASP.NET MVC Input
    1. Form 結構
    2. 字串輸入 String Input
    3. 日期選擇器 DateTimePicker
    4. 下拉式選單

儘管 Asp.net MVC 5 預設的 Bootstrap 套件是 3 ,但 Bootstrap 已進展到 4 ,同時正朝向 5 邁進,同時也提供更豐富的 helper,而兩者在表單定義也有所不同,因此獨立以新的筆記紀錄關於新版本 Bootstrap 在 MVC 中表單設計的相關筆記。

logo

ASP.NET MVC Input

Form 結構

@using (Html.BeginForm()) { @Html.AntiForgeryToken()

<div class="form-horizontal">
  <hr />
  @Html.ValidationSummary(true, "", new { @class = "text-danger" })
  <div class="form-group">
    ...
  </div>
</div>
} @section scripts{
<script>
  $(document).readt(function(){
      ...
  });
</script>
}

字串輸入 String Input

<div class="form-group">
  <span class="ml-4 badge-info p-1">單欄位</span>
  @Html.LabelFor(model => model.TextCol, htmlAttributes: new { @class =
  "control-label col-md-2" })
  <div class="col-md-10">
    @Html.EditorFor(model => model.TextCol, new { htmlAttributes = new { @class
    = "form-control " } }) @Html.ValidationMessageFor(model => model.TextCol,
    "", new { @class = "text-danger" })
  </div>
</div>

<div class="form-group">
  <span class="ml-4 badge-info p-1">雙欄位</span>
  @Html.LabelFor(model => model.TextCol, htmlAttributes: new { @class =
  "control-label col-md-2" })
  <div class="col-md-10">
    <div class="row">
      <div class="col-md-6">
        @Html.EditorFor(model => model.TextCol, new { htmlAttributes = new {
        @class = "form-control " } })
      </div>
      <div class="col-md-6">
        @Html.EditorFor(model => model.TextCol, new { htmlAttributes = new {
        @class = "form-control " } })
      </div>
    </div>
    @Html.ValidationMessageFor(model => model.TextCol, "", new { @class =
    "text-danger" })
  </div>
</div>

日期選擇器 DateTimePicker

筆記連結

下拉式選單

/Controller

var dropDownList = new List<SelectListItem>();

foreach (var item in db.DropListTable.ToList())
{
    dropDownList.Add(
      new SelectListItem() { 
        Text = item.DropdownName, Value = item.DropdownId.ToString(), Selected = false 
    });
}

ViewBag.dropDownList = dropDownList.AsEnumerable();

/View

<div class="form-group">
    <span class="ml-4 badge-info p-1">下拉式選單</span>
    @Html.LabelFor(model => model.DropdownCol, htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownListFor(model => model.DropdownCol, (IEnumerable<SelectListItem>)ViewBag.dropDownList, new { @class = "form-control w-25" })
        @Html.ValidationMessageFor(model => model.DropdownCol, "", new { @class = "text-danger" })
    </div>
</div>