通过剃刀列表循环和添加项目之间的分隔符 [英] Looping through a list in razor and adding a separator between items
问题描述
我有我想要的剃刀视图输出项目的列表。各项目之间,我想添加一个分隔线,像这样的:
I have a list of items which I want to output in a razor view. Between each item I want to add a separator line, like this:
item1 | item2 | item3
通过项目环最简单的方法是用一个foreach:
The simplest way to loop through items is with a foreach:
@foreach(var item in Model.items){
<span>@item.Name</span> |
}
不幸的是这会增加在列表的最后一个额外的分隔线。有没有一种简单的方法来跳过这最后的分割线?
Unfortunately this adds an extra separator line at the end of the list. Is there a simple way to skip this last separator line?
推荐答案
您可以使用的string.join:
You can use string.Join:
@Html.Raw(string.Join("|", model.Items.Select(s => string.Format("<span>{0}</span>", s.Name))))
使用的string.join
否定需要检查的最后一个项目。
Using string.Join
negates the need to check for the last item.
您可以用剃刀混合此 @helper
用于更复杂的标记方法:
You can mix this with a Razor @helper
method for more complex markup:
@helper ComplexMarkup(ItemType item)
{
<span>@item.Name</span>
}
@Html.Raw(string.Join("|", model.Items.Select(s => ComplexMarkup(s))))
您甚至可以创建一个辅助方法来抽象 Html.Raw()
和的string.join()
电话:
You could even create a helper method to abstract the Html.Raw()
and string.Join()
calls:
public static HtmlString LoopWithSeparator
(this HtmlHelper helper, string separator, IEnumerable<object> items)
{
return new HtmlString
(helper.Raw(string.Join(separator, items)).ToHtmlString());
}
用法:
@Html.LoopWithSeparator("|", model.Items.Select(s => ComplexMarkup(s)))
这篇关于通过剃刀列表循环和添加项目之间的分隔符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!