ASP.NET MVC: Display List data in a view

If you want to display a IEnumerable<x> List in a View, you cannot use standard ASP.NET WebForms Controls like a ListView to iterate over a list. The reason here is mostly because of the fact that MVC 2 does not implement the Form-ViewState.

11 January 2011
Christoph Keller Christoph Keller

If you want to display a IEnumerable<x> List in a View, you cannot use standard ASP.NET WebForms Controls like a ListView to iterate over a list. The reason here is mostly because of the fact that MVC 2 does not implement the Form-ViewState.

Now if you need to do this, you can just iterate over the List you got by using a standard foreach:

<ul id="menu">
    <% foreach (var navItem in Model) { %>
        <li><%:Html.ActionLink(navItem.Title, navItem.TargetAction, navItem.TargetController)%></li>
    <% } %>
</ul>

In the above example, the View is a strongly-typed view, which inherits from 'System.Web.Mvc.ViewUserControl<IEnumerable<Common.DataAccess.INavigationItem>>', so I can just iterate over the ViewModel and get a IEnumerable<INavigationItem>.


comments powered by Disqus