How to get multi selected values from a Selectlist
?
Here is what I tried so far: following code below gets only gets the one value so issue might be with line Colors = Request.Query["Colors"];
<form asp-page="./index" method="get">
<select asp-for="Colors" asp-items="@Model.Colors_SELECT" multiple>
<option value="">All</option>
</select>
</form>
url example: https://localhost:7221/Index?Colors=&Blk&Colors=red&Colors=blue
back-end code
[BindProperty(SupportsGet = true)]
public string? Colors { get; set; }
public SelectList? Colors_SELECT { get; set; }
public async Task OnGetAsync()
{
// Fill select values
Colors_SELECT = new SelectList(_services.Fill_Colors(), "Value", "Text", 1);
// selected values
Colors = Request.Query["Colors"];
}
helper function to fill colors
public List<SelectListItem> Fill_Colors()
{
List<SelectListItem> Query = new List<SelectListItem>
{
new SelectListItem() { Value = "Black", Text = "blk" },
new SelectListItem() { Value = "red", Text = "red" },
new SelectListItem() { Value = "blue", Text = "blue" }
};
return Query;
}
CodePudding user response:
You need to change the type of the Colors
property to string array:
public string[]? Colors { get; set; }
Then when OnGetAsync
is called the Colors
array will contain the values from the query string.
[BindProperty(SupportsGet = true)]
public string[]? Colors { get; set; }
public SelectList? Colors_SELECT { get; set; }
public async Task OnGetAsync()
{
// Fill select values
Colors_SELECT = new SelectList(_services.Fill_Colors(), "Value", "Text", 1);
// selected values
foreach(var color in Colors)
{
Console.WriteLine(color);
}
// https://localhost:7221/Index?Colors=black&Colors=red&Colors=blue
// will print: "black", "red", "blue"
}