如何在ASP.NET Razor视图中将布尔值替换为Yes/No显示?
实现方案
你可以通过以下几种方式实现把布尔值转换成"Yes"/"No"显示:
方法一:直接使用三元运算符(最简便)
在视图的表格单元格中,用C#的三元条件运算符直接判断布尔值,输出对应的文本:
修改后的完整代码:
@using ToDoListApp.Models @model List<TodoTable> <table class="table table-hover"> <thead> <tr> <th scope="col">ID</th> <th scope="col">Task</th> <th scope="col">Urgent</th> <th scope="col">Done</th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <th scope="row">@item.Id</th> <td>@item.Name</td> <td>@(item.Urgent ? "Yes" : "No")</td> <td>@(item.Done ? "Yes" : "No")</td> </tr> } </tbody> </table>
核心就是把@item.Urgent改成@(item.Urgent ? "Yes" : "No"),括号是为了让Razor正确解析表达式。
方法二:扩展方法(更优雅,适合多处复用)
如果你的项目里很多地方都需要把布尔值转成"Yes"/"No",可以给bool类型写一个扩展方法:
- 在项目中新建一个静态类(比如
BoolExtensions.cs):
namespace ToDoListApp.Extensions { public static class BoolExtensions { public static string ToYesNo(this bool value) { return value ? "Yes" : "No"; } } }
- 在视图顶部引入扩展方法的命名空间:
@using ToDoListApp.Extensions @using ToDoListApp.Models @model List<TodoTable>
- 然后在表格里直接调用扩展方法:
<td>@item.Urgent.ToYesNo()</td> <td>@item.Done.ToYesNo()</td>
这种方式让视图代码更简洁,而且逻辑复用性强。
内容的提问来源于stack exchange,提问作者Emir Bolat
相关产品推荐
相关产品推荐

