Html.DisplayFor can automatically iterate over collections, displaying a partial view for each element in the collection.
The first thing you need to do is create an actual model class, with the collection being a property of the class.
public class Bar
{
public IEnumerable<Foo> foo { get; set; }
}
Return this class from your controller instead of the raw collection.
Secondly you need a display template for the Foo class. Display templates are partial views that need to be placed in the folder Views/Shared/DisplayTemplates
.
Edit: You can have them in your controller subfolder of Views as well if you want to limit the template to a particular controller. See this question for more information.
Here is an example in razor syntax:
@model YourNameSpace.Foo
<p>@Model.BarBaz</p>
Save it as Foo.cshtml
in the DisplayTemplates
folder given above.
This template is pretty simple because it is based on your example where you are only displaying a string, but if the collection elements where a class with its own properties you could create a more elaborate template.
Now in the original view, you can get rid of the loop entirely and just write
@Html.DisplayFor(m => m.foo)
Notice foo
is the name of the property in your new model class that contains the old collection you looped over before.
DisplayFor will automatically know that the foo
property is of type (collection of) Foo
and pick up the Foo.cshtml
template in the DisplayTemplates
folder and show it once for each element in foo
.