【问题标题】:How to add css class dyanmically to Select List Item in DropDownList Razor如何动态添加 css 类以在 DropDownList Razor 中选择列表项
【发布时间】:2021-03-14 08:42:27
【问题描述】:

您好,我想在 MVC Razor 语法中的 DropDowList 中的特定 SelectListIem 中添加一个 CSS 类。

我实际上想实现一个 CSS:

new SelectListItem{ Text="Out Of 5", Value = "Out Of 5"},

而不是为整个控件实现。

下面是sn-p的代码:

@Html.DropDownList("Options", new List<SelectListItem>
{
   new SelectListItem{ Text="Select Options", Value = "1" },
   new SelectListItem{ Text="CheckBox", Value = "1" },
   new SelectListItem{ Text="Radio", Value = "2" },
   new SelectListItem{ Text="Rating", Value = "3"},
   new SelectListItem{ Text="Out Of 5", Value = "Out Of 5"},
   new SelectListItem{ Text="Out Of 10", Value = "Out Of 10"},
   new SelectListItem{ Text="Text", Value = "4"},
}, new { @class = "form-control input-group, dropdown-submenu" })







                            
    
                           

【问题讨论】:

    标签: css asp.net-core model-view-controller razor


    【解决方案1】:

    这里有两种解决方案:

    第一个(foreach 下拉选项,如果 text="Out Of 5",添加类):

    @Html.DropDownList("Options", new List<SelectListItem>
    {
       new SelectListItem{ Text="Select Options", Value = "1" },
       new SelectListItem{ Text="CheckBox", Value = "1" },
       new SelectListItem{ Text="Radio", Value = "2" },
       new SelectListItem{ Text="Rating", Value = "3"},
       new SelectListItem{ Text="Out Of 5", Value = "Out Of 5"},
       new SelectListItem{ Text="Out Of 10", Value = "Out Of 10"},
       new SelectListItem{ Text="Text", Value = "4"},
    }, new { @class = "form-control input-group, dropdown-submenu",@id="select" })
    <script>
        $(function () {
            $("#select > option").each(function () {
                if (this.text == "Out Of 5") {
                    $(this).addClass("special");
                }
            });
        })
    </script>
    <style>
        .special {
            color:red;
        }
    </style>
    

    2.第二个(把selectlistItem改成,加class到&lt;option value="Out Of 5" class="special"&gt;Out Of 5&lt;/option&gt;):

    <select class="form-control input-group, dropdown-submenu">
        <option value="1">Select Options</option>
        <option value="1">CheckBox</option>
        <option value="2">Radio</option>
        <option value="3">Rating</option>
        <option value="Out Of 5" class="special">Out Of 5</option>
        <option value="Out Of 10">Out Of 10</option>
        <option value="4">Text</option>
    <style>
        .special {
            color:red;
        }
    </style>
    

    结果:

    【讨论】:

      猜你喜欢
      • 2014-10-28
      • 1970-01-01
      • 1970-01-01
      • 2021-09-24
      • 2015-06-15
      • 2010-12-16
      • 1970-01-01
      • 2014-02-18
      • 1970-01-01
      相关资源
      最近更新 更多