[asp.net-mvc] MVC Razor @foreach

I heard that having @foreach inside of a view is a no-no. Meaning, the view should not have any logic in it. What is the best practice on where the logic for the @foreach should be at?

    @foreach.. 

This question is related to asp.net-mvc razor

The answer is


a reply to @DarinDimitrov for a case where i have used foreach in a razor view.

<li><label for="category">Category</label>
        <select id="category">
            <option value="0">All</option>
            @foreach(Category c in Model.Categories)
            {
                <option title="@c.Description" value="@c.CategoryID">@c.Name</option>
            }
        </select>
</li>

I'm using @foreach when I send an entity that contains a list of entities ( for example to display 2 grids in 1 view )

For example if I'm sending as model the entity Foo that contains Foo1(List<Foo1>) and Foo2(List<Foo2>)

I can refer to the first List with:

@foreach (var item in Model.Foo.Foo1)
{
    @Html.DisplayFor(modelItem=> item.fooName)
}

When people say don't put logic in views, they're usually referring to business logic, not rendering logic. In my humble opinion, I think using @foreach in views is perfectly fine.


The answer will not work when using the overload to indicate the template @Html.DisplayFor(x => x.Foos, "YourTemplateName) .

Seems to be designed that way, see this case. Also the exception the framework gives (about the type not been as expected) is quite misleading and fooled me on the first try (thanks @CodeCaster)

In this case you have to use @foreach

@foreach (var item in Model.Foos)
{
    @Html.DisplayFor(x => item, "FooTemplate")
}