【问题标题】:Populate SelectList with Font-Awesome Icons in ASP.NET MVC在 ASP.NET MVC 中使用 Font-Awesome 图标填充 SelectList
【发布时间】:2021-12-03 17:07:13
【问题描述】:

我已经用字体很棒的字符串填充了列表,例如:

    private static readonly List<string> Icons = new(){
        "<i class=\"fas fa-users\"></i>",
        "<i class=\"fas fa-user-tag\"></i>",
        "<i class=\"fas fa-sitemap\"></i>",
        "<i class=\"fas fa-cubes\"></i>",
        "<i class=\"fas fa-shield-alt\"></i>"
    };

在视图中我有一个下拉列表:

<select asp-for="Icon" class="form-control" asp-items="ViewBag.Icons"></select>

然后当我在 SelectList 中显示它们时,我得到:

我想将它们呈现为 html 并显示图标,而不是字符串。可能吗?也许用 JS 或 jQuery?

【问题讨论】:

  • 我认为没有 hacks 是不可能的,afaik 选项元素不支持其中的 html,因此您必须创建一个行为类似于 select 的自定义元素
  • 是否有可能使用 jQuery 或仅使用 JS?
  • 我认为这是可能的,看看这里w3schools.com/howto/howto_custom_select.asp
  • 如果我没记错的话,Tag Helper is for ASP.NET Core MVC。您可以将问题标签更改为.net-coreasp.net-core-mvcasp.net-core 相关标签。

标签: c# asp.net .net asp.net-mvc razor


【解决方案1】:

您不能在&lt;option&gt; 元素中呈现&lt;i&gt; 图标元素,如以下问题:Font Awesome icon in select option

相反,您可以将 Unicode 传递给 &lt;option&gt; 元素以显示图标。

第 1 步:从 FontAwesome website 获取图标的 Unicode。

第 2 步:将图标的 Unicode 传递给 SelectList

注意1:传递给前端的Unicode格式必须是:&amp;#x{Unicode};

注意2:您可以删除&lt;i&gt;元素字符串并重新设计Icons类型,以防&lt;i&gt;元素不需要。

控制器

public IActionResult Index()
{
    Dictionary<string, string> Icons = new Dictionary<string, string>()
    {
        { "<i class=\"fas fa-users\"></i>", "&#xf0c0;" },
        { "<i class=\"fas fa-user-tag\"></i>", "&#xf507;" },
        { "<i class=\"fas fa-sitemap\"></i>", "&#xf0e8;" },
        { "<i class=\"fas fa-cubes\"></i>", "&#xf1b3;" },
        { "<i class=\"fas fa-shield-alt\"></i>", "&#xf3ed;" }
    };

    ViewBag.Icons = new SelectList((IEnumerable)Icons, "Key", "Value");
}

第 3 步:使用 @Html.Raw(item.Text) 渲染 &lt;option&gt; 元素。

注意:Unicode 将生成为IHtmlString 而不是string

查看

<head>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.0/css/all.min.css" />

    <style>

        select {
            font-family: 'FontAwesome', Verdana;
        }

        .fa option {
            font-weight: 900;
        }
    </style>
</head>
<select asp-for="Icon" class="form-control fa">
    @foreach (var item in (SelectList)ViewBag.Icons)
    {
        <option value="@item.Value">
            @Html.Raw(item.Text)
        </option>
    }
</select>

结果

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-04
    • 2013-01-22
    • 2016-11-13
    • 2013-10-21
    • 2015-09-02
    • 1970-01-01
    • 2013-08-11
    相关资源
    最近更新 更多