Loop through Model items in ASP.NET MVC

Loop through Model items in ASP.NET MVC

To loop through Model items in ASP.NET MVC view, use foreach loop in the Controller,which returns Collection of items.

Add the given below line to bind your model with .cshtml page.

  1. 1: @model IEnumerable<BookStore.Models.Category>  

Now write foreach loop at view level page(.cshtml).

  1. @if (Model != null)  
  2.    {  
  3.        foreach (var item in Model)  
  4.        {  
  5.        <ul id="menu">  
  6.   
  7.            <li>  
  8.                @Html.DisplayFor(modelItem => item.Address)  
  9.            </li>  
  10.            <li>  
  11.                @Html.DisplayFor(modelItem => item.City)  
  12.                <br />  
  13.            </li>  
  14.   
  15.            <li>  
  16.                @Html.DisplayFor(modelItem => item.Id)  
  17.            </li>  
  18.        </ul>  
  19.        }  
  20.    }  


Ebook Download
View all
Learn
View all