简体   繁体   中英

Access Json objects data returned by Controller in MVC 4

I'm having trouble figuring out a way to access the following json returned from my controller:

[{"ID":1,"seatnum":"A1","status":0},{"ID":2,"seatnum":"A2","status":0}]

I am trying to to access the each seatnum value (A1, A2) to perform the following function:

$.ajax({
    url: 'seats/getseats',
    dataType: "JSON",
    error: function (data) {
        $("table tr img").removeClass("available").attr("src", "images/taken.gif");
        alert("error")
    }
}).done(function (data) {


    for (var i = 0; i < data.length; i++) {
        //alert(data[i].seatnum);
        var seatLetter = data[i][0];
        var seatNumber = data[i].substr(1);
        var $target = getImgFromSeat(seatLetter, seatNumber);
        $target.removeClass("available").attr("src", "images/taken.gif");

    }

If it helps my Controller method is:

//
    // GET: /seats/

    public ActionResult Index()
    {
        return View(db.seats.ToString());
    }

    public JsonResult getseats()
    {


        var taken = from b in db.seats
                         select b;

        taken = taken.Where(b => b.status.Equals(0));
        return Json(taken, JsonRequestBehavior.AllowGet);
    }

I believe that you are looking for something like:

$.ajax({
  type: "GET",
  url: '@Url.Action("getseats")',
  contentType: "application/json; charset=utf-8",
  dataType: "json",
  success: successFunc,
  error: errorFunc
});

function successFunc(data, status) {
  for (var i = 0; i < data.length; i++) {
    //alert(data[i].seatnum);
    var seatLetter = data[i][0];
    var seatNumber = data[i].substr(1);
    var $target = getImgFromSeat(seatLetter, seatNumber);
    $target.removeClass("available").attr("src", "images/taken.gif");    
  }
}

function errorFunc() {
  alert('error');
}

The returned json is an array of objects, so instead of accessing it like data[i][0] you should access it like data[i].seatnum, data[i].status, etc.

Additionally I recommend you to use some debugging tools like your browsers developer tools so you can inspect the values of different objects.

PS: do not hard-code the URL value. Instead use @Url.Action("action-name") to generate it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM