Nils Anders
Nils Anders

Reputation: 4410

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);
}

Upvotes: 8

Views: 14334

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038930

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.

Upvotes: 6

Ravi Gadag
Ravi Gadag

Reputation: 15861

you need to add JsonRequestBehavior.AllowGet in your json method

from Phil haack post JsonHijacking

By default, the ASP.NET MVC framework does not allow you to respond to an HTTP GET request with a JSON payload. If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet as the second parameter to the Json method. However, there is a chance a malicious user can gain access to the JSON payload through a process known as JSON Hijacking. You do not want to return sensitive information using JSON in a GET request.

Upvotes: 1

Related Questions