简体   繁体   中英

Prepopulating <select multiple> form-control

I'm trying to preselect multiple values in a <select multiple class=form-control> element. I'm using ASP.Net Core and RAZOR to render the html.

At the top of the html file, I define the long list of fruits that I want displayed in the multiselect box. Later on, I iterate through the list and get the fruits the user previously selected and try to show the option in the list as selected.

@{  
    var allFruitsList = new List<string>() 
        {"strawberries","blueberries","bananas","kiwis",
         "apples", "raspberries", "pears"};

    var profile = ViewData["UserFavoriteFruit"];
    var myFaveFruits = profile.MyFavoriteFruits; //would be List<string>
}

This is the section of code where I go through the fruits previously selected to know which ones I want to appear as selected on page load

<select multiple class="form-control" id="myMultiselect">
    <option disabled> - - - - - Select Favorite Fruit - - - - -</option>
        @foreach (var v in allFruitsList)
        {
            if (myFaveFruits.Contains(@v))
            {
                <option selected>@v</option>
            }
            else
            {
                <option>@v</option>
            }
        }
</select>

I've tried many different things including :

  1. <option selected="true">@v</option>
  2. <option selected="selected">@v</option>
  3. <option selected>@v</option>
  4. <option selected="selected" value=@v>@v</option>
  5. <option onload="MakeSelectionLookSelected()"></option>
  6. <option onload="MakeSelectionLookSelected('@v')" id='@v'>@v</option>

     MakeSelectionLookSelected() { $(this).click(); } MakeSelectionLookSelected() { $(this).change(); } MakeSelectionLookSelected(id) { $("#"+id).click(); } MakeSelectionLookSelected(id) { $("#"+id).change(); } 

None of these approaches are working. What's weird is that when I use the DOM explorer, the code reflects that the correct <option> elements are being tagged with the "selected" attribute, but the UI is not displaying the blue box fill around the entries that are supposed to be selected...

Anyone know what I'm doing wrong? What else I can try? If bootstrap multiple select does not allow prepopulating? What a good alternative is?

Figured out a solution!

So I needed to add the "selectpicker" class. https://silviomoreto.github.io/bootstrap-select/

so now my field looks as follows:

<select multiple class="selectpicker form-control" id="myMultiselect">

when using selectpicker by itself, the formatting looks off, but using both helps stylize it as well

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM