MVC - List (bullet list numbered list)
by
Jeremy Canfield |
Updated: March 20 2020
| MVC articles
First, let's add the values to the HomeController.cs file:
public ActionResult Index()
{
ViewBag.names = new List<string>()
{
"Jeremy",
"Natalie",
"Winston"
};
return View();
}
Next, let's loop through the list:
- In Solution Explorer, expand Views > Home, and select Index.cshtml
- Right-click anywhere in the HomeController.cs and select Add View
- In the Add View pop-up box, keep the defaults and select Add
- Enter the following markup:
Note: In this markup, strName is the name of the variable. This can be anything you choose. ViewBag.names is the list you want to use in the HomeController.cs file.
<ul>
@foreach(string strName in ViewBag.names)
{
<li>@strName</li>
}
</ul>
This can also be accomplished using ViewData instead of ViewBag.
public ActionResult Index()
{
ViewData["names"] = new List<string>()
{
"Jeremy",
"Natalie",
"Winston"
};
return View();
}
<ul>
@foreach(string strName in (List<string>)ViewData[\"names\"])
{
<li>@strName</li>
}
</ul>
Did you find this article helpful?
If so, consider buying me a coffee over at