Search code examples
javascriptc#jqueryasp.net-mvc-5jquery-select2-4

Select2 Set Values for Multi-Select in MVC


I am working on a project which uses select2 multi-selects on part of the forms. This code works great for the Create page, but when I go to the Edit page, I run into a problem. I want to be able to take the values I have from creating the "Items" and then use jQuery to set the values on the Edit page for those "Items."

Here's what I have:

var re = /[0-9]+$/;
$('#Item').select2({
    theme: "bootstrap",
    placeholder: "Not Set",
    tags: true
});

$('#Item').on("select2:select", function (evt) {
    var element = evt.params.data.element;
    var $element = $(element);
    $element.detach();
    $(this).append($element);
    $(this).trigger("change");
});

var values = "@Model.ItemIds"; //pull ItemIds from Model in MVC
$.each(values.split(","), function (i, e) {
    if (e != "Not Set" && e != "" && e != null && e != undefined) {
        if (!re.test(e)) {
            var newList = $.merge($('#Item').select2('data'), [{
                id: e,
                tag: e
            }]);
            $("#Item").select2('data', newList);
            $("#Item").append('<option value="' + e + '">' + e + '</option>');
        }
    $("#Item option[value=" + e + "]").prop("selected", true);
    }
});

So, what happens is that when the page loads I get the Items that are selected are the ones in @Model.ItemIds, but they are in the order that they are listed under the <select> not the order that they are in @Model.ItemIds. Any help would be appreciated. Thanks!


Solution

  • Here's my new code:

    var values = "@Model.ItemIds"; //pull ItemIds from Model in MVC
    $.each(values.split(","), function (i, e) {
        if (e != "Not Set" && e != "" && e != null && e != undefined) {
            if (!re.test(e)) {
                var newList = $.merge($('#Item').select2('data'), [{
                    id: e,
                    tag: e
                }]);
                $("#Item").select2('data', newList);
                $("#Item").append('<option value="' + e + '">' + e + '</option>');
            }
            else{
                $("#Item").append($("#Item option[value='" + e + "']"));
            }
        $("#Item option[value='" + e + "']").prop("selected", true);
        }
    });
    

    Appending the existing option to the end seems to have fixed my issue.