Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to return json and populate selectlist

Im trying to return a Json result from my controller and populate a selectlist using jQuery. But the code dont even hit the Json method in my controller.

My selectlist

<select id="MyList"></select>

My javascript

<script type="text/javascript">
    $(document).ready(function () {
        $.getJSON("@Url.Action("GetProductJson", "Product")", 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);
            });
        });
    };
</script>

My Json method in ProductController

[HttpGet]
public JsonResult GetProductJson()
{
    var list = new List<SelectListItem>
           {
               new SelectListItem { Value = "1", Text = "Aron" },
               new SelectListItem { Value = "2", Text = "Bob" },
               new SelectListItem { Value = "3", Text = "Charlie" },
               new SelectListItem { Value = "4", Text = "David" }
           };

    return Json(list);
}
like image 571
Nils Anders Avatar asked Jan 22 '13 09:01

Nils Anders


1 Answers

You should enable JSON for GET requests which is disabled by default. This happens by passing a second argument to the Json method:

return Json(list, JsonRequestBehavior.AllowGet);

Now go ahead and install FireBug. If you had done that prior to posting this question on StackOverflow you could have inspected the AJAX request in your browser and could have seen that the server returns 500 status code and when you inspected the response you would have seen the exact error message and not only that - you would also have seen a suggestion on how to fix it. The suggestion is basically what I posted here in my answer. Thus you wouldn't even had the need to post your question as you would be able to solve it by yourself. I cannot possibly imagine people doing web development without a tool such as FireBug or Chrome Developer Tools. It's like trying to build a house with your own bare hands and without any tools.

like image 83
Darin Dimitrov Avatar answered Oct 02 '22 09:10

Darin Dimitrov