You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在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类型写一个扩展方法:

  1. 在项目中新建一个静态类(比如BoolExtensions.cs):
namespace ToDoListApp.Extensions
{
    public static class BoolExtensions
    {
        public static string ToYesNo(this bool value)
        {
            return value ? "Yes" : "No";
        }
    }
}
  1. 在视图顶部引入扩展方法的命名空间:
@using ToDoListApp.Extensions
@using ToDoListApp.Models
@model List<TodoTable>
  1. 然后在表格里直接调用扩展方法:
<td>@item.Urgent.ToYesNo()</td>
<td>@item.Done.ToYesNo()</td>

这种方式让视图代码更简洁,而且逻辑复用性强。

内容的提问来源于stack exchange,提问作者Emir Bolat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.19 15:20:51