Looping through a list in razor and adding a separator between items

前端 未结 4 774
温柔的废话
温柔的废话 2021-01-02 03:08

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
         


        
4条回答
  •  时光取名叫无心
    2021-01-02 03:48

    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 items)
    {
        return new HtmlString
              (helper.Raw(string.Join(separator, items)).ToHtmlString());
    }
    
    
    

    Usage:

    @Html.LoopWithSeparator("|",  model.Items.Select(s => ComplexMarkup(s)))
    

    提交回复
    热议问题