store array in viewbag and retrieving in the view

In this post, we will discuss about how to store the array in view bag and how to use them in view.

Controller

A simple Controller action which store the string array in the ViewBag and return to the view.

public ActionResult Index()
{
string[] Countries = {“India”, “US”,”Nepal” };
ViewBag.Countries = Countries;
return View();
}

View

<h2>List Of Cities</h2>
@foreach (string city in ViewBag.Countries) {
<li>@city
</li>
}

OUTPUT :

6 thoughts on “store array in viewbag and retrieving in the view”

  1. the solution is good and working.I have another example:
    Controller:
    string[] UnitIDs = { “CSQ-1001”, “CSQ-1002”, “CSQ-1003”, “CSQ-1004”, “CSQ-1005”, “CSQ-1006″ };
    ViewBag.UnitIDs = UnitIDs;
    return View();
    View:

    Please select a truck unit id

    Choose a Truck Id
    @foreach (string unitID in ViewBag.UnitIDs)
    {
    @unitID
    }

    you can remove the asp-for=”SelecATruckUnitId”, since I used it from a @model, you may not need it

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.