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