Bootstrap FreeKB - MVC - List (bullet list numbered list)
MVC - List (bullet list numbered list)

Updated:   |  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:

  1. In Solution Explorer, expand Views > Home, and select Index.cshtml
    1. Right-click anywhere in the HomeController.cs and select Add View
    2. In the Add View pop-up box, keep the defaults and select Add
  2. 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 Buy Me A Coffee



Comments


Add a Comment


Please enter f8d531 in the box below so that we can be sure you are a human.