Steve
Steve

Reputation: 3080

Trying to access class passed back via JSON

I am calling this function via a JSON object

    [AcceptVerbs(HttpVerbs.Get)]
    public JsonResult GetMatchDetails(int id)
    {
        var match = GetRepository<Match>().Get(id);

        return Json(match, JsonRequestBehavior.AllowGet);
    }

where the var match is from the class (trimed down version but im not needing to use the rest)

 public class Match : Entity
 {
    public virtual DateTime? MatchDate { get; set; }
    public virtual ICollection<Boxer> Boxers { get; set; }
    public virtual string Location { get; set; }
    public virtual MatchResult Result { get; set; }
    public virtual int Rounds { get; set; }
 }

and the call from the javascript is (from the function called)

        var matchStuff = null;
        //Get a class which will have the Match and two boxers part of it
        $.getJSON("/BoxingPredictionLeague/GetMatchDetails/" + MatchId, function(data){
            matchStuff = data;
            alert(matchStuff.Id);

        });

Where the alert is I have tried to alert out the Id using matchStuff[0].Id as well as matchStuff.Id but it doesnt alert at all... seems to just be crashing or that object is null!

Upvotes: 1

Views: 141

Answers (1)

TheRightChoyce
TheRightChoyce

Reputation: 3084

Obvious questions:

Are you sure you're getting an object returned from your repository?

Are you sure there's a 'Id' property? (its not listed in the code sample)

Otherwise:

If you use chrome, you can do the following to see exactly what is being returned via Json.

  1. Goto Tools -> Developer Tools
  2. Click on 'Resources'
  3. Underneath those buttons there's a little bar, click on XHR.
  4. On the left you'll see all the ajax calls the page initiated. Headers will show what you're sending; content will show what you've received. The content is straight JSON, but you should be able to determine it from there.

If you're using firebug:

  1. Open firebug via the icon on the bottom left (ensure its enabled)
  2. Click on the 'Net' tab
  3. Underneath those buttons there's a little bar, click on XHR.
  4. You'll see a list of all ajax calls. expanding one will enable you to see both the headers and the content response.

One of these two methods should help you track it down --otherwise everything else looks correct via your code sample.

Upvotes: 1

Related Questions