Contents tagged with Json

  • 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>
    
  • Json, jQuery and ASP.NET MVC

    aspnetI’m stacking a few things here related to Json, jQuery and ASP.NET MVC so that I can get to them later on.

    JQuery to grab some Json when a web page is loaded:

    $(document).ready(function() {
        $.getJSON("/MyController/MyJsonAction", null, function(data) {
    //do stuff with data here
    }); });

    The smallish code in the ASP.NET MVC controller:

    public JsonResult GetJson()

    {

        return Json(GetList());

    }

    It’s possible to use anonymous types with Json() as well, which is very useful but may be harder to unit test.