我有一组在MVC3 Razor中重复的字符串,代码如下:
@if (Model.Publications != null)
{
<tr>
<th>Publications</th>
<td>
@foreach (var publication in @Model.Publications)
{
<text>@publication.Title</text>
}
</td>
</tr>
}
现在当我展示这个时,我得到的只是:
Book1Book2Book3
但我真的想要的是这样的:
Book1, Book2, Book3
MVC剃刀是否有一种简单的方法可以实现这一点,而无需将'if'和'foreach'语句结合起来?
答案 0 :(得分:5)
string.Join(", ", model.Publications.Select(pub => pub.Title).ToArray())
答案 1 :(得分:5)
@string.Join(",",Model.Publications.Select(p=>"<text>"+ p.Title+ "</text>"))
答案 2 :(得分:1)
@if (Model.Publications != null)
{
<tr>
<th>Publications</th>
<td>
@var first = true
@foreach (var publication in @Model.Publications)
{
<text>@string.format("{0}{1}", first ? "" : ", ", publication.Title)</text>
@first = false;
}
</td>
</tr>
}