Search code examples
c#asp.net-coretag-helpers

simple asp.net tag helper list<> question


I am not sure if you can even do this, I am just learning and experimenting some.

In a cshtml file I have:

@{ 
List<string> items = new List<string>();
items.Add("item 1");
items.Add("item2");

}

Then I want to just access that in a select:

            <td><select asp-for="Genre" asp-items=@items /></td>

Is there a way to do this or I am just trying to feed a baseball to a horse who really wants an apple?


Solution

  • You can try to use List<SelectListItem> instead of List<string>

    The SelectListItem class belongs to Microsoft.AspNet.Mvc.Rendering namespace.

    @{ 
    
        List<SelectListItem> items= new List<SelectListItem>()
        {
            new SelectListItem {Text = "item1", Value = "item1"},
            new SelectListItem {Text = "item2", Value = "item2"}
        };
    }
    
    <td><select asp-for="Genre" asp-items="@items"></select></td>