nam nam - 3 months ago 35
C# Question

Select Tag Helper binding with an array or list

How can my following controller Action Method bind a list of integers to a

Select Tag Helper
in my ASP.NET Core project
without using ModelView
? Or, without ModelView this cannot be done?

Action Method:

public IActionResult ListofDays()
{
IEnumerable<int> DaysList = Enumerable.Range(1, 7).ToList();
return View(DaysList);
}


Select Tag:

<select asp-for="???" asp-items="???"></select>

Answer

You can convert the int array to a list of SelectListItem which can be used as your asp-items property value of select tag helper.

public IActionResult Index()
{
    var daysList =Enumerable.Range(1, 7)
       .Select(g => new SelectListItem {Value = g.ToString(), Text =g.ToString()}).ToList();
    return View(daysList);
}

Now in the view which is strongly typed to a list of SelectListItem,

@model List<SelectListItem>
<form asp-action="Index" asp-controller="Home">
    <select name="MyDay" asp-items="Model"></select>
    <input type="submit"/>
</form>

When you submit the form, the selected day will be in the MyDay form element. You may use a parameter with the same name in your HttpPost action method to receive it.

For your reference : Select Tag Helper in MVC 6

Comments