How to display a bullet or numbered list in MVC using view

Home > Search > How-to
  by

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>

 



Add a Comment




We will never share your name or email with anyone. Enter your email if you would like to be notified when we respond to your comment.




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




Comments