title: Select2 Set Values for Multi-Select in MVC
body: <p>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."</p>
  
  <p>Here's what I have:</p>
  
  <pre><code>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" &amp;&amp; e != "" &amp;&amp; e != null &amp;&amp; e != undefined) {
          if (!re.test(e)) {
              var newList = $.merge($('#Item').select2('data'), [{
                  id: e,
                  tag: e
              }]);
              $("#Item").select2('data', newList);
              $("#Item").append('&lt;option value="' + e + '"&gt;' + e + '&lt;/option&gt;');
          }
      $("#Item option[value=" + e + "]").prop("selected", true);
      }
  });
  </code></pre>
  
  <p>So, what happens is that when the page loads I get the Items that are selected are the ones in <code>@Model.ItemIds</code>, but they are in the order that they are listed under the <code>&lt;select&gt;</code> not the order that they are in <code>@Model.ItemIds.</code> Any help would be appreciated. Thanks!</p>