Marco Dinatsoli
Marco Dinatsoli

Reputation: 10570

jquery MVC4 receive JSON

I want to send json data from my controller to my view when a specific action happens.

I used this on controller to send the data

[HttpGet] 
 public JsonResult JSONGetParking(int buildingID){

     return this.Json(
                          new
                          {
                              Result = (from obj in db.Parkings.Where(p => p.buildingID == buildingID) select new { ID = obj.ID, Name = obj.note })
                          }
                          , JsonRequestBehavior.AllowGet
                       );
}

it works very good

on my script i used this:

FloorScript.js

$(document).ready(function () {
        $('#buildingID').change(function () {
            alert("what is not");
            $.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
                alert("afd");
                var items = " ";
                $.each(data, function (obx, oby) {
                    items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
                });
                $('#parkingID').html(items);
            });
        });
    });

I have opened google chrome and I can see the request and the response like this:

enter image description here

i can see the two text that i alerted

However, on my selector, i just see undefined value

Html

<div id="editor-label">
        <select id="parkingID" name="parkingID"></select>
    </div>

I have added the jquery in this

@section scripts {
    @Scripts.Render("~/bundles/jqueryval")
    @Scripts.Render("~/Scripts/FloorScript.js");
}

Upvotes: 2

Views: 164

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

You're not looping on the correct variable.

You did this:

$.each(data, function (obx, oby) {

whereas you should do this:

$.each(data.Result, function (obx, oby) {

This is pretty visible in the Google Chrome screenshot you provided. As you can see the returned JSON has a property called Result which is the collection whereas you were looping over the data variable which is not an array - it's just a javascript object that has a property called Result which is the array you wanna be looping through.

Also I'd replace:

$.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {

with:

$.getJSON('JSONGetParking', { buildingID: $('#buildingID').val() }, function (data) {

and of course get rid of this hardcoded url over there and use an url helper to generate it, on the dropdown as an HTML5 data-* attribute:

@Html.DropDownListFor(
    x => x.BuildingId, 
    Model.Buildings, 
    new { 
        id = "buildingID", 
        data_url = Url.Action("JSONGetParking") 
    }
)

and then inside the change event you can trivially easy retrieve this url and avoid hardcoding it (and of course taking the risk of breaking your code when you deploy it in IIS in a virtual directory or simply change the routing pattern of your application):

$('#buildingID').change(function () {
    var url = $(this).data('url');
    $.getJSON(url, { buildingID: $('#buildingID').val() }, function (data) {

Alright, now the initial mess is tidied up.

Upvotes: 3

C M
C M

Reputation: 703

use data.Result in your each loop

$(document).ready(function () {
        $('#buildingID').change(function () {
            alert("what is not");
            $.getJSON('JSONGetParking?buildingID=' + $('#buildingID').val(), function (data) {
                alert("afd");
                var items = " ";
                $.each(data.Result, function (obx, oby) {
                    items += "<option value='" + oby.ID + "'>" + oby.Name + "</option>";
                });
                $('#parkingID').html(items);
            });
        });
    });

Hope this helps...

Upvotes: 2

Related Questions