title: Fill Select2 dropdown box from database in MVC 4
body: <p>I need help writing the jquery/ajax to fill a <a href="http://ivaynberg.github.io/select2/index.html">Select2</a> dropdown box.</p>
  
  <p><em>For those who don't know what <a href="http://ivaynberg.github.io/select2/index.html">Select2</a> is, it is a javascript extension to provide Twitter Bootstrap looks and search / type-ahead functionality to an html select list dropdown box. For more information look at the examples here: <a href="http://ivaynberg.github.io/select2/index.html">Select2 Github page</a></em> 
  <hr>
  <strong>UPDATED - Solved!</strong></p>
  
  <hr>
  
  <p>So I finally put this all together, and the solution to my problems was that I was missing functions to format the results and the list selection. The code below produces a functioning <a href="http://ivaynberg.github.io/select2/index.html">Select2</a> dropbox with type-ahead perfectly.</p>
  
  <p>Json Method on Controller:</p>
  
  <pre><code>public JsonResult FetchItems(string query)
  {
      DatabaseContext dbContext = new DatabaseContext(); //init dbContext
      List&lt;Item&gt; itemsList = dbContext.Items.ToList(); //fetch list of items from db table
      List&lt;Item&gt; resultsList = new List&lt;Item&gt;; //create empty results list
      foreach(var item in itemsList)
      {   
          //if any item contains the query string
          if (item.ItemName.IndexOf(query, StringComparison.OrdinalIgnoreCase) &gt;= 0) 
          {
              resultsList.Add(item); //then add item to the results list
          }
      }
      resultsList.Sort(delegate(Item c1, Item c2) { return c1.ItemName.CompareTo(c2.ItemName); }); //sort the results list alphabetically by ItemName
      var serialisedJson = from result in resultsList //serialise the results list into json
          select new
          {
              name = result.ItemName, //each json object will have 
              id = result.ItemID      //these two variables [name, id]
          };
      return Json(serialisedJson , JsonRequestBehavior.AllowGet); //return the serialised results list
  }
  </code></pre>
  
  <p>The Json controller method above returns a list of serialised Json objects, whose ItemName contains the string 'query' provided (this 'query' comes from the search box in the <a href="http://ivaynberg.github.io/select2/index.html">Select2</a> drop box).</p>
  
  <p>The code below is the Javascript in the view(or layout if you prefer) to power the <a href="http://ivaynberg.github.io/select2/index.html">Select2</a> drop box.</p>
  
  <p>Javascript:</p>
  
  <pre><code>$("#hiddenHtmlInput").select2({
      initSelection: function (element, callback) {
          var elementText = "@ViewBag.currentItemName";
          callback({ "name": elementText });
      },
      placeholder: "Select an Item",
      allowClear: true,
      style: "display: inline-block",
      minimumInputLength: 2, //you can specify a min. query length to return results
      ajax:{
          cache: false,
          dataType: "json",
          type: "GET",
          url: "@Url.Action("JsonControllerMethod", "ControllerName")",
          data: function (searchTerm) {
              return { query: searchTerm };
          },
          results: function (data) { 
              return {results: data}; 
          }
      },
      formatResult: itemFormatResult,
      formatSelection: function(item){
          return item.name;
      }
      escapeMarkup: function (m) { return m; }
  });
  </code></pre>
  
  <p>Then in the body of the view you need a hidden Input element, which <a href="http://ivaynberg.github.io/select2/index.html">Select2</a> will render the dropbox to.</p>
  
  <p>Html:</p>
  
  <pre><code>&lt;input id="hiddenHtmlInput" type="hidden" class="bigdrop" style="width: 30%" value=""/&gt;
  </code></pre>
  
  <p>Or attach a MVC Razor html.hidden element to your view model to enable you to post the picked item Id back to the server.</p>
  
  <p>Html (MVC Razor):</p>
  
  <pre><code>@Html.HiddenFor(m =&gt; m.ItemModel.ItemId, new { id = "hiddenHtmlInput", @class = "bigdrop", style = "width: 30%", placeholder = "Select an Item" })
  </code></pre>