如何根据整数字段在Razor页面正确输出Glyphicon图标?
Fixing Glyphicon Display Based on Integer Status in Razor Pages
Hey, let's get that Glyphicon issue sorted out for you. I can see two key problems with your current code that are making the icons show up incorrectly, and I'll walk you through two solid solutions to fix it.
First, let's break down the root of the problem:
- Razor isn't properly parsing your inline conditional expression. When you write
@item.Status == 0 ?  : , it's treating the whole line as plain text instead of evaluating the condition and outputting the right icon. - Directly using HTML entity codes like
inside a Razor expression won't render as the actual icon character unless you handle encoding correctly.
Solution 1: Use Glyphicon CSS Classes (Recommended)
Glyphicons are built to work with specific CSS classes—this is the cleaner, more maintainable approach. Instead of hardcoding character entities, assign the appropriate class based on your Status value:
@foreach (var item in Model) { <tr> <td> <span class="glyphicon @(item.Status == 0 ? "glyphicon-ok" : "glyphicon-remove")"></span> </td> <!-- Add your other table cells here --> </tr> }
Why this works:
- The
@()syntax tells Razor to evaluate the conditional expression and output the resulting class string. - Bootstrap's Glyphicon CSS automatically applies the correct icon font character based on the class you pick (e.g.,
glyphicon-okrenders a checkmark,glyphicon-removerenders an X). You can swap these out for any Glyphicon class that fits your status logic—likeglyphicon-pauseorglyphicon-info-sign.
Solution 2: Output the Icon Character Directly (If You Prefer)
If you need to use raw Unicode characters instead of CSS classes, you'll need to use C# Unicode escape sequences and make sure Razor renders the character properly:
@foreach (var item in Model) { <tr> <td> <span class="glyphicon"> @(item.Status == 0 ? "\uE157" : "\uE067") </span> </td> <!-- Add your other table cells here --> </tr> }
Why this works:
\uE157is the C# equivalent of the HTML entity(the checkmark icon), and\uE067maps to the X icon.- The
@()wrapper ensures Razor evaluates the conditional and outputs the actual Unicode character, not the escape sequence text. - You still need the
glyphiconclass to apply Bootstrap's correct font family and styling to the character.
Quick Troubleshooting
If icons still don't show up:
- Double-check that you've included the Bootstrap CSS file in your page (Glyphicons are part of Bootstrap's default styles).
- Verify your Status values are correctly set to 0 or the expected integer.
- Confirm the Glyphicon class or Unicode character matches the exact icon you want to display.
内容的提问来源于stack exchange,提问作者Rod
相关产品推荐
相关产品推荐

