I have a select list:
[BindProperty]
public List<SelectListItem> FooList { get; set; }
The list is then instantiated as an empty list and the razor page loads. The list is then populated by the user on the client side using jquery. The server doesn't know the items in the list until the form is posted. So far, so good.
In the page I'm using the select tag helpers like so...
<select asp-for="FooList" multiple="multiple" asp-items="FooList" class="form-control form">
I'm wondering how can I retrieve all items in a mulitple selectlist "list box" (whether they're selected or not) OnPost using model binding?
I'm using razor pages 2.2 and I'm really struggling to figure this out.
public IActionResult OnPost()
{
// not sure how to get the selectlist and all of its items?
foreach (var item in FooList)
{
// do stuff with the items
}
return Page();
}
I know it's got to be something simple, just need a fresh set of eyes to point me in the right direction. Thanks!
I'm wondering how can I retrieve all items in a mulitple selectlist "list box" (whether they're selected or not) OnPost using model binding?
You can't. Only the values of the selected items are posted and can take part in model binding. If you want to get the selected items in a multiple select list, you need to bind them to a collection. Your asp-for
attribute should reference the name of the collection that you are binding the posted values to. You should not have [BindProprty]
on the List<SelectListItem>
type. They only represent the items that populate the select list.
You can find out more about the basics of Select Lists in Razor Pages here.