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?
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?
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.
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:
@foreach (var item in Model.Foos)
{
<div>@item.Bar</div>
}