select下拉框分组使用bootstrap select

HTML5 <optgroup>标签用来定义一个选项组,即,可以将文档中的选项进行组合。

select标签使用<optgroup>分组:

<select>
  <optgroup label="Swedish Cars">
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
  </optgroup>
  <optgroup label="German Cars">
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </optgroup>
</select> 

效果如图:

 

 

 

不太美观,可以使用bootstrap select,asp.net mvc core的cshtml页面动态加载如下(引用对应css和js后,class增加selectpickerdata-live-search是否使用模糊搜索框):

<select class="form-control selectpicker" data-live-search="true">
    <option selected="selected">请选择</option>
    @{
        if (list != null)
        {
            var firstlist = list.Where(o => o.Pid == null).ToList();
            if (firstlist?.Count > 0)
            {
                @foreach (var item in firstlist)
                {
                    var sublist = list.Where(o => o.Pid != null && o.Pid == item.Id).ToList();
                    <optgroup label="@item.Name">
                        @if (sublist?.Count > 0)
                        {
                            @foreach (var subitem in sublist)
                            {
                                <option value="@subitem.Id">@subitem.Name</option>
                            }
                        }
                    </optgroup>
                }
            }
       }
    }
</select>                

效果如下:

 

 

参考:

select动态分组(这个用的select2):https://blog.csdn.net/torpidcat/article/details/103785353

<optgroup>标签解释和效果:https://www.w3cschool.cn/html5/html5-optgroup.html

posted @ 2020-11-28 22:45  户的博客  阅读(1909)  评论(0编辑  收藏  举报