0

I'm using this code to generate a multi-select2. Tags is a MultiSelectList.

@Html.DropDownList("mail-to", (IEnumerable<SelectListItem>)ViewBag.Tags, String.Empty, htmlAttributes: new { multiple = "", @class = "form-control select2 select2-multiple" })

$("#mail-to").select2({
           minimumResultsForSearch: -1,
           closeOnSelect: false,
       });

It works great. Now I want to change the select options with another ViewBag based on a checkbox field checked change event. Is there a way to change select2 data populated with this type of list or a MVC way to do it?

What I've tryed:

$("#mail-to").select2({
    tags: @ViewBag.TagsArea, //or tags: @Html.Raw((IEnumerable<SelectListItem>)ViewBag.TagsArea)
                    });
Rubén M
  • 107
  • 1
  • 1
  • 13
  • Not related, but it needs to be `ListBox()`, not `DropDownList()` - refer [this answer](https://stackoverflow.com/questions/40725358/why-does-the-dropdownlistfor-lose-the-multiple-selection-after-submit-but-the-li/40732481#40732481) –  Apr 11 '18 at 09:48
  • And it would be `tags: @Html.Raw(Json.Encode(ViewBag.TagsArea)),` to convert the `IEnumerable` to a javascript array –  Apr 11 '18 at 09:50
  • Changed to list box, thanks for the info. But is not working, writing tags that way gives `Option tags is not allowed for Select2 when attached to a – Rubén M Apr 11 '18 at 10:13
  • What version of select2 are you using? – Water Cooler v2 Apr 11 '18 at 10:33
  • Was using 4.0.2, updated to 4.0.6, still same issue – Rubén M Apr 11 '18 at 12:04

1 Answers1

0

Managed to solve it:

var areas = @Html.Raw(Json.Encode(ViewBag.Tags)) ;    
$("#mail-to").empty();
     $.each(areas, function (index, element) {
         $("#mail-to").append($('<option/>', {
            value: element.Value, text: element.Text
             }));
     });
Rubén M
  • 107
  • 1
  • 1
  • 13