Moataz Alsayed
Moataz Alsayed

Reputation: 381

Asp.net Core, set multiple selected values in Razor Page

So, I am trying to create a multi-select dropdown list and I want to set some default selected values in it.
I get the values and store them in an array of strings containing the values in each one.
I tried to set them as 1 string and it didn't work, tried setting them as an array of strings and it didn't work as well.

Here is the code:

<select name="FacultyList" multiple class="sel form-control" asp-for="Faculties" 
id="uniFaculties" asp-items="@(new SelectList(facultyList,"Name","Name",@selectedFaculties))">
</select> 

facultyList is a list of values I get from and api.
selectedFaculties is an array of strings that contains the selected values.

Note: I'm using the Chosen jQuery library as well if that makes a difference.

Upvotes: 2

Views: 2771

Answers (1)

John H
John H

Reputation: 14655

There is a MultiSelectList that you can use for this:

new MultiSelectList(facultyList, "Name", "Name", @selectedFaculties)

I just noticed from your code that you're using asp-for on the select. When doing that, the selected values you pass to either SelectList or MultiSelectList will be ignored. The reason is because it's expecting the selected values to be in the Faculties property that you're binding to. In case you run into that, here is a working example for you.

View

<select name="FacultyList" multiple class="sel form-control" asp-for="SelectedFaculties"
    id="uniFaculties" asp-items="@(new MultiSelectList(Model.AvailableFaculties, "Name", "Name"))">
</select> 

Controller

public IActionResult Faculty()
{
    var vm = new FacultyViewModel
    {
        AvailableFaculties = new List<Faculty>
        {
            new Faculty
            {
                Name = "Arts"
            },
            new Faculty
            {
                Name = "Science"
            },
            new Faculty
            {
                Name = "Mathematics"
            }
        },
        SelectedFaculties = new List<string> { "Arts", "Mathematics" }
    };

    return View(vm);
}

This will select Arts and Mathematics. Notice that the selected values are coming from the same property that we're binding the select to using asp-for, and that we're no longer passing selected values to the MultiSelectList directly.

Upvotes: 2

Related Questions