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

如何在Razor视图中无需foreach方法显示List<Answer>数据

在Razor视图中无foreach显示List内容

没问题,要在Razor视图里展示List<Answer>的内容又不想用foreach的话,String.Join是最直接高效的方案,下面给你几种适配不同显示需求的实现方式(假设你的Answer类有一个用于展示的字符串属性,比如Text,如果是其他名称你替换成自己的即可):

方法1:简单逗号分隔显示

这是最基础的用法,直接把所有答案用逗号分隔成一段文本:

<td>
    @String.Join(", ", Model.Answers.Select(a => a.Text))
</td>

方法2:每行显示一个答案

如果需要每个答案单独换行,用<br/>标签分隔,注意要使用Html.Raw来渲染HTML标签,同时用Html.Encode避免XSS风险:

<td>
    @Html.Raw(String.Join("<br/>", Model.Answers.Select(a => Html.Encode(a.Text))))
</td>

方法3:无序列表样式展示

要是想让答案以列表形式呈现,可以生成<ul>和<li>标签,同样借助Html.Raw来渲染:

<td>
    <ul>
        @Html.Raw(String.Join("", Model.Answers.Select(a => $"<li>{Html.Encode(a.Text)}</li>")))
    </ul>
</td>

完整的视图代码示例

把上面的方法整合到你现有的代码里,完整的表格部分大概是这样:

@model PoolManager.Models.Question
@{
    ViewData["Title"] = "Details";
}

<h2>Details</h2>

<table class="table">
    <thead>
        <tr class="bg-primary">
            <th>Question</th>
            <th>Answers</th>
            <th>Starting Date</th>
            <th>Ending Date</th>
            <th>Active</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>@Model.QuestionText</td> <!-- 替换成你Question类里的问题文本属性 -->
            <td>
                <!-- 这里选择上面任意一种方法即可 -->
                @String.Join(", ", Model.Answers.Select(a => a.Text))
            </td>
            <td>@Model.StartingDate.ToString("yyyy-MM-dd")</td> <!-- 可选:格式化日期显示 -->
            <td>@Model.EndingDate.ToString("yyyy-MM-dd")</td>
            <td>@(Model.Active ? "Yes" : "No")</td> <!-- 可选:把布尔值转成友好文本 -->
        </tr>
    </tbody>
</table>

这些方法之所以不用写foreach,是因为String.Join会在底层帮我们遍历集合并完成内容拼接,完全符合你的需求~

内容的提问来源于stack exchange,提问作者dorin munteanu

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:28:11