Fill a Select/Option from Json with jQuery

aspnetMore jQuery and Json…

To fill a listbox (select) with items from a Json call.

I got this helper class to handle the options/items:

public class SelectOption
{
    public String Value { get; set; }
    public String Text { get; set; }
}

A sample action/method in ASP.NET MVC that returns Json:

public JsonResult GetJson()
{
    var list = new List<SelectOption>
                   {
                       new SelectOption { Value = "1", Text = "Aron" },
                       new SelectOption { Value = "2", Text = "Bob" },
                       new SelectOption { Value = "3", Text = "Charlie" },
                       new SelectOption { Value = "4", Text = "David" }
                   };
    return Json(list);
}

Some HTML and jQuery to fill the list at page load:


    <select id="MyList" />

    <script type="text/javascript">

        $(document).ready(function() {
            $.getJSON("/Json/GetJson", null, function(data) {
                $("#MyList").addItems(data);
            });
        });

        $.fn.addItems = function(data) {
            return this.each(function() {
                var list = this;
                $.each(data, function(index, itemData) {
                    var option = new Option(itemData.Text, itemData.Value);
                    list.add(option);
                });
            });
        };

        $("#MyList").change(function() {
            alert('you selected ' + $(this).val());
        });

    </script>

No Comments