首页 > 解决方案 > MVC 和 Bootstrap 4:使用 DropDownListFor 更改生成的按钮标签的样式

问题描述

在我的 ASP.NET MVC Core Web 应用程序中,我通过 .cshtml 文件中的以下代码生成下拉列表:

<div>
    @Html.DropDownListFor(x => x.SelectedType,
        new SelectList(Model.Types, "TypeId", "Name"), "Select one...",
        new
        {
            @class = "selectpicker",
            data_show_subtext = "false",
            data_live_search = "true"
        })
</div>

顺便说一句,我bootstrap-select也在使用图书馆。

当我在 Chrome 中检查页面时,这会生成以下 HTML:

<div>
<div class="dropdown bootstrap-select">
    <select class="selectpicker" data-live-search="true" data-show-subtext="false" data-val="true" data-val-required="Type is required."
        id="SelectedType" name="SelectedType" tabindex="-98">
        <!-- option tags omitted -->
    </select>
    <button type="button" class="btn dropdown-toggle btn-light" data-toggle="dropdown" role="button" data-id="SelectedType" title="X">
        <div class="filter-option">
            <div class="filter-option-inner">
                <div class="filter-option-inner-inner">X</div>
            </div>
        </div>
    </button>
    <div class="dropdown-menu " role="combobox">
        <div class="bs-searchbox">
            <input type="text" class="form-control" autocomplete="off" role="textbox" aria-label="Search">
        </div>
        <div class="inner show" role="listbox" aria-expanded="false" tabindex="-1">
            <ul class="dropdown-menu inner show"></ul>
        </div>
    </div>
</div>
</div>

一切都很好。但是,使用 Bootstrap 4,我发现自己需要将btn-light类更改btn-outline-secondary<button>标签中的。

如何通过 HtmlHelperDropDownListFor方法执行此操作?

我当然可以在 JS 中做一些后期渲染的东西,比如

$(".dropdown-toggle").removeClass("btn-light").addClass("btn-outline-secondary");

...但这似乎是一个后备选项,并不是最佳选择。

标签: asp.net-core-mvcbootstrap-4html-helperbootstrap-select

解决方案


推荐阅读