2

I have a seemingly very small problem, but I can't find a solution for it:

Within a Razor view i have something like this:

<p>
@if (someCondition){
   foreach (Sometype s in Model.ListOfSomeTypes){
      @s.Name @//There is a space in front here.
   }
}
</p>

But I want to have to have all the names comma seperated, so i essentially want to do something like this:

<p>
@if (someCondition){
   foreach (Sometype s in Model.ListOfSomeTypes){
      @s.Name, 
   }
}
</p>

However, Razor freaks out. How can I achieve this kind of result?


I have tried some variations like this:

@{','} @s.Name @//No good
@"," @s.Name @//No good
@{","} @s.Name @//No good
@StringVariableContainingComma @s.Name @//This works, but seems to be very unnessecary to me.

Ps. I know that the above suggested solution for comma seperated elemens don't work propperly. Removed conditions for easier reading of question.

4

4 回答 4

4

使用常规括号指定显式代码块

@(s.Name), @(...)
于 2012-10-15T21:05:02.973 回答
4

<text>标签应该为你做。

<p>
@if (someCondition){
   foreach (Sometype s in Model.ListOfSomeTypes){
      @s.Name<text>, </text>
   }
}
</p>
于 2012-10-15T21:09:52.443 回答
1

这应该可以 - 虽然你会有尾随逗号

@foreach (Sometype s in Model.ListOfSomeTypes){
    @(s.Name+",")
}

或者

@if (someCondition){
   @String.Join(",", Model.ListOfSomeTypes.Select(s => s.name));
}
于 2012-10-15T21:09:36.157 回答
0
<p>
@if (someCondition){
   foreach (Sometype s in Model.ListOfSomeTypes){
      @s.Name<span>, </span>@s.City
   }
}
</p>

您可以使用跨度标签

于 2021-02-01T22:29:37.280 回答