Something you might be repeating while building a user interface is populating a select box with JSON results. Here is a quick demonstration on a very simple way to do this. Put the ‘populateSelect’ method in a global .js file and use it throughout your project as ‘$.populateSelect(args…)’

ASP.NET MVC Action Method

public ActionResult GetUsers()
{
     var data = Service.QueryUsers()
           .Select(x => new {value = x.Id, text = x.Name});

      return Json(data);
}

Usage:

var url = "<%=Url.Action("GetUsers", "UserController") %>";

$.getJSON(url, function(data, textstatus) {
        $.populateSelect("#someSelectBox", data);
});

Global Method:

// JQuery Method
jQuery.populateSelect = function(selectId, data) {
    $.each(data, function() {
        var option = new Option(this.text, this.value);
        var dropdownList = $(selectId)[0];
        if ($.browser.msie) {
            dropdownList.add(option);
        } else {
            dropdownList.add(option, null);
        }
    });
};

Removing all Items from a select list is just as simple:

$("#mySelectList")
   .find("option")
   .remove();

And lastly how to Append or Prepend items to the list:

// Add options to the end of a select
$("#mySelectList")
    .append("");

// Add options to the start of a select
$("#mySelectList")
    .prepend("");

Leave a Reply