How to use foreach loop in ASP.NET MVC .cshtml file?

Asked 3 years ago Updated 1 year ago 2229 views

2 Answers


0

In an ASP.NET MVC .cshtml file, you can use the foreach loop inside Razor syntax to iterate over a collection and generate dynamic HTML.

Example 1: Iterating Over a List in the View

If you pass a list from the controller to the view, you can loop through it in the .cshtml file.

Controller (HomeController.cs)

public ActionResult Index()
{
    List<string> names = new List<string> { "Alice", "Bob", "Charlie" };
    return View(names);
}

View (Index.cshtml)

@model List<string>

<ul>
    @foreach (var name in Model)
    {
        <li>@name</li>
    }
</ul>

Output:

  • Alice 
  • Bob 
  • Charlie
0
@foreach (var item in Model.Foos)
{
    <div>@item.Bar</div>
}

Write Your Answer