C# MVC Razor 下拉選單(單選)(多選)(篩選) using [select2]套件
C# MVC Razor 下拉選單(單選)(多選)(篩選) using [select2]套件
C#
List<SelectListItem> list_SelectListItem = new List<SelectListItem>();
list_SelectListItem.Add(new SelectListItem() { Text = "", Value = "" });
foreach (var ima in list_Data)
{
SelectListItem sli = new SelectListItem();
sli.Value = ima.Data01;
sli.Text = $"{ima.Data01} | {ima.Data02}";
list_SelectListItem.Add(sli);
}
ViewBag.list_SelectListItem = list_SelectListItem;
HTML
<link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-beta.1/dist/js/select2.min.js"></script>
<div>
@Html.DropDownList("DropDownList_Data1", list_SelectListItem, "", new { @class = "form-control js-example-basic-single", style = "max-width:1000px;width:1000px;" })
<button type="button" class="btn btn-info" data-type="Create" id="btn_IMA">
<span class="glyphicon glyphicon-file" style="margin-right:5px;"></span>Show
</button>
</div>
<p></p>
<div>
@Html.ListBox("DropDownList_Data2", list_SelectListItem, new { @class = "form-control js-example-basic-multiple", style = "max-width:1000px;width:1000px;" })
<button type="button" class="btn btn-info" data-type="Create" id="btn_IMA2">
<span class="glyphicon glyphicon-file" style="margin-right:5px;"></span>Show
</button>
</div>
Javascript
$(function () {
$('.js-example-basic-single').select2();
$('.js-example-basic-multiple').select2();
});
$(document).on('click', '#btn_IMA', function () {
let data = $('#DropDownList_Data1').val();
alert(data);
});
$(document).on('click', '#btn_IMA2', function () {
let data = $('#DropDownList_Data2').val();
alert(data);
});
說明
DropDownList_Data1 為單選, 可以篩選資料, 資料取得為Value的資料
- 使用@Html.DropDownList
DropDownList_Data2 為多選, 可以篩選資燉, 資料取得為多筆Value的資料, 使用逗號分隔。
- 使用@Html.ListBox
select2套件資源: https://select2.org/getting-started/basic-usage
留言
張貼留言