Search code examples
c#asp.net-mvc-4razor-2

Inner helper with different conditions in foreach loop, how to manage that?


Inner helper with different conditions in foreach loop, how to manage that?

I want to have different foreach loop, but the rest of the helper should be the same Different version

   1 - foreach (var item in Model.Where(_ => _.Version > 0))
   2 - foreach (var item in Model.Where(_ => _.Version = 0))
   3 - foreach (var item in Model)

Any suggestions?

 @helper WriteGrid()
 {
  foreach (var item in Model.Where(_ => _.Version > 0))
  {
    <div>
     @item.From
    </div>
  }
}

Solution

  • You can change your @helper a bit to take a Func<T,bool> which can decide which items to show:

    @helper WriteGrid(Func<MyModel, bool> p)
    {
        foreach (var item in Model.Where(p))
        {
            <div>@item.From</div>
        }
    }
    
    @WriteGrid(x => x.Version > 0)
    <hr/>
    @WriteGrid(x => x.Version == 0)
    <hr/>
    @WriteGrid(x => true)
    <hr/>