views:

42

answers:

3

I'm having troubles reading a Json result back from a controller method...

I have this method in my controller:

    [AcceptVerbs(HttpVerbs.Post)]
    public JsonResult GetCurrent()
    {
        IList<string> profile = new List<string>();
        profile.Add("-1");
        profile.Add("Test");
        profile.Add("");

        return this.Json(profile);
    }

And it is being called by this jquery ajax post:

$.post("/Profile/GetCurrent", function(profile) { profileCompleteOpen(profile); }, "json");

and the javascript function called on the post's callback:

function profileCompleteOpen(profile) {
   alert(profile);
   alert(profile[0]);
}

The result of the first alert shows the array like this:

["-1","Test",""]

But the result of the second alert shows this:

[

rather than

-1

What am I doing wrong here... I've compared it to one of the other times I'm doing this and it seems to be the exact same. Why isn't it recognizing it's an array?

Thanks,
Matt

A: 

Hmmm, I'd be doing what you're trying to do a little differently.

I'd either return a fully qualified object and then use it's properties;

class MyObj
{
  public string name{get;set;}
}

fill the object and return it as a json object. then you're jquery code can access like any other object.

The other way might be to do a return PartialView("MyView", model);

That will return the partial view as html back to your page which you can then append to your html.

griegs
A: 

I think the type of profile is string instead of array. Why? Check the $.post method parameters. Maybe the problem is there.

$.post("url", null, function(profile) { ... }, "json");
Mehdi Golchin
+1  A: 

Try converting the json data in profile to a proper object by using eval() on it.

Example:

var profileObject = eval('(' + profile + ')');
Terje
Worked perfectly, thanks!
Matt