Is it bad practice to use foreach inside the View?

Asked

Viewed 340 times

3

It’s a bad practice to use foreach within the View? If it is, how to do it?

  • 4

    Not... This is normal. Quite common in the construction of Tables.

  • Does not depend on the foreach and yes of the Ienumerable that you are using in the loop. foreach in itself is as valid as if

2 answers

4

Not!

Bad practice is to carry out business rules in the view. Another very common bad practice is code repetition, copy and paste always the same code instead of creating a partial view.

But, for foreach only, it is impossible to say. Bad practice may be on what you are doing in the loop, but not because you are using it.

3


Is bad practice?

No. The foreach can be used to display data in the View normally.

Example: Assuming that my model (Product-type class viewmodel) has a list of products and I wish to display the name and value of each product.

@model ProdutosViewModel
    ...
    @foreach produto in Model.Produtos
    {
        //Código para exibir dados do produto
        <tr>
         <td>@produto.Nome</td>
         <td>@produto.Valor</td>
        </tr>
    }
    ...

But if you have too many records to iterate it is interesting to use a pagination feature for example, even for a better user experience.

When people say no logic in the View, they are usually referring to business logic. Once you are using the foreach just to display information on the page is not a bad practice to use it in the View.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.