Johan's Blog

This and that in a developer's life in general
Welcome to Blogs @ IRM Sign in | Join | Help
 Search

Disclaimer

The content of this site is my own personal opinion and does not in any way represent my employer, it's subsideries or affiliates. These postings are provided "AS IS" with no warranties, and confer no rights.

This Blog

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>

Cross-posted from my blog at http://weblogs.asp.net/jdanforth
Published den 3 april 2009 14:19 by johan
Filed under: , ,

Comment Notification

If you would like to receive an email when updates are made to this post, please register here

Subscribe to this post's comments using RSS

Comments

No Comments

Leave a Comment

(required) 
(optional)
(required) 
Submit
Powered by Community Server, by Telligent Systems