0

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

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

3 Comments

I've updated my question to show my ajax request to the get seats action method
Please try my approach. Also you did not mention what kind of error are you getting.
data[i].seatnum isn't selecting each seatnum only data[0].seatnumetc seems to work

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.