'ASP.NET MVC - Populate SelectList with Font-Awesome Icons

I've populated List with font-awesome strings like:

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>"
};

And in View I have a dropdown:

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

and then when I display them in SelectList I get:

enter image description here

I would like to render them as HTML and display icons, not strings. Is it possible? Maybe with JS or jQuery?



Solution 1:[1]

You cannot render <i> icon element in <option> element as asked this question: Font Awesome icon in select option.

Instead, you can pass the Unicode to the <option> element in order to show the icon.

Step 1: Get the icons' Unicode from FontAwesome website.

Step 2: Pass the icons' Unicode to SelectList.

Note 1: The Unicode that passed to front-end must be in the format: &#x{Unicode};

Note 2: You may remove <i> element string and redesign Icons type in case <i> element is not needed.

Controller

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");
}

Step 3: Render <option> elements with @Html.Raw(item.Text) .

Note: Unicode to be generated as IHtmlString instead of string.

View

<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>

Result

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Yong Shun