Is it bad practice to use foreach
within View ? If so, how?
Is it bad practice to use foreach
within View ? If so, how?
Is it bad practice?
No. The foreach can be used to display data in the View normally.
Example: Assuming my model (type of ProductsViewModel type) has a list of products and I want 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's interesting to use a paging feature for example, even for a better user experience.
When people say they do not put logic in the View, they are generally referring to business logic. Since you are using foreach only to display information on the page it is not a bad practice to use it in the View.
No!
Bad practice is to conduct business rules in the view. Another very common bad practice is repeating code, copying and pasting the same code instead of creating a partial view.
But by foreach only, it is impossible to say. Bad practice might be in what you're doing in the loop, but not because you're using it.