如何使用标签助手或 html 助手在选择选项中显示字体真棒图标?



我已经遵循了这个问题中的答案,但我只得到了字符代码,例如 在我的<option>中以纯文本形式&#xf007;

在我的控制器中,我填充了SelectList的项目:

public IActionResult Create()
{
ViewData["Icons"] = IconsDropdown();
return View();
}
private SelectList IconsDropdown()
{
List<ListItem> list = new List<ListItem>()
{
new ListItem{ Text = "&#xf007;", Value = "fa-user" },
new ListItem{ Text = "&#xf508;", Value = "fa-user-tie" },
// and so on...
};
return new SelectList(list, "Value", "Text");
}
class ListItem
{
public string Text { get; set; }
public string Value { get; set; }
}

然后,我将列表项分配给视图中的select

<select asp-for="Icon" class="form-control select-fontawesome" asp-items="ViewBag.Icons">
<option selected disabled value="">Choose icon</option>
</select>

我也尝试删除类form-control,但结果相同。

用于设置字体的 CSS:

.select-fontawesome {
font-family: 'FontAwesome', 'sans-serif';
}

如果我尝试在普通文本中显示 FontAwesome 图标,它可以工作:

<span class="fas fa-user"></span>

更新

感谢@MBaas指出我需要<select>上的fa类和<option>上的style="font-weight:900;"类。

但是使用标签助手,无法在<option>上设置样式,因此解决方案不起作用。

我一直在寻找一种使用@Html.DropDownListFor()而不是标签助手的方法,但到目前为止,我还没有发现它会让我在<option>s 中添加 css 样式。我可以在<select>-tag 上设置一个类,但仅此而已:

@Html.DropDownListFor(m => 
m.Icon, 
ViewBag.Icons, 
"Choose icon", 
new { @class= "form-control fa" })

我见过一些示例,这些示例似乎可以在没有任何其他 CSS 或类的情况下工作 - 但不知何故,我可以按照这些思路生成一些东西。但是以下内容对我有用;)

将类fa应用于select控件(该位随 FontAwesome 一起提供(,然后对选项进行一些样式设置,以确保它们是带有font-weight: 900的样式。fa也这样做,但它似乎被浏览器的设置覆盖了。然后,我们的设置将覆盖浏览器。

<link href="https://use.fontawesome.com/releases/v5.0.13/css/all.css" rel="stylesheet"/>
<style>
select.fa option {font-weight: 900}
</style>
<select name="sample" id="sample" class="fa">
<option value="">Choose icon</option>
<option value="fa-user">&#xf007;</option>
<option value="fa-user-tie">&#xf508;</option>    
</select>

最新更新