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
You can use string.Join
:
@Html.Raw(string.Join("|", model.Items.Select(s => string.Format("{0}", s.Name))))
Using string.Join
negates the need to check for the last item.
You can mix this with a Razor @helper
method for more complex markup:
@helper ComplexMarkup(ItemType item)
{
@item.Name
}
@Html.Raw(string.Join("|", model.Items.Select(s => ComplexMarkup(s))))
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
Usage:
@Html.LoopWithSeparator("|", model.Items.Select(s => ComplexMarkup(s)))