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

Asked 19-Aug-2022
Updated 12 days ago
Viewed 542 times

1

I want to show multiple records in a list on the page in MVC. I want to use foreach loop for it, anyone can help me how to apply it?


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>
}