How to add class to index.cshtml

849 views Asked by At

I need to create drop down list that includes 5 different cities using yield return new SelectListItem

This is a part of the code in my newly made class called listOfCities

public static IEnumerable<SelectListItem> GetItems()
{
    List<SelectListItem> list = new List<SelectListItem>();
    list.Add(new SelectListItem { Text = "City", Value = "City" });
    SelectListItem item = new SelectListItem();
    yield return new SelectListItem
    {
        Text = "London",
        Value = "London"
    };

This is my code in index.cshtml

@Html.DropDownListFor(model => model.City,listOfCities.GetItems())

When I write this code, it gives me:

THE NAME 'listOfCities' DOES NOT EXIST IN THE CURRENT CONTEXT

Where is the problem?

1

There are 1 answers

6
Jasen On

You need to add a using for the namespace for your listOfCities class in the view.

@using My.Namespace;

@Html.DropDownListFor(model => model.City,listOfCities.GetItems())

Or write out the full namespace

@Html.DropDownListFor(model => model.City, My.Namespace.listOfCities.GetItems())