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>", "" },
{ "<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>", "" }
};
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
