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

前端 未结 4 751
温柔的废话
温柔的废话 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:51

    Keep a counter variable and inside the loop and check whether it is the last item or not.

    @{ int counter=0; }
    @foreach(var item in Model.items){
      counter++;
      @item.Name
      if(counter

    and the short version is

    @{ int counter=0; }
    @foreach(var item in Model.items){
      counter++;
      @item.Name @(counter< Model.items.Count?"|":"")
     } 
    

提交回复
热议问题