Getting index value on razor foreach

前端 未结 10 754

I\'m iterating a List in a razor foreach loop in my view which renders a partial. In the partial I\'m rendering a single record for which I want to hav

10条回答
  •  死守一世寂寞
    2020-12-08 09:54

    All of the above answers require logic in the view. Views should be dumb and contain as little logic as possible. Why not create properties in your view model that correspond to position in the list eg:

    public int Position {get; set}
    

    In your view model builder you set the position 1 through 4.

    BUT .. there is even a cleaner way. Why not make the CSS class a property of your view model? So instead of the switch statement in your partial, you would just do this:

    Move the switch statement to your view model builder and populate the CSS class there.

提交回复
热议问题