John Edwards
John Edwards

Reputation: 1546

Can't access JSON object

I am using asp mvc and am returning a json object to my view, and I cannot seem to access any of the properties in the json. Here is my code.

In my Model I have:

public string getJson()
{ 
    File a = new File();
    a.Name = "matt";
    a.Path = "c:/adsgadsg/sdagdsag";
    string json = new JavaScriptSerializer().Serialize(a);
    //json = "{\"Name\":\"matt\",\"Path\":\"c:/adsgadsg/sdagdsag\"}"   
    return json;
}

Then in my javascript I have:

function test() {
    var userRegion = '@Model.getJson()';
    var tmp = userRegion.Name;
    var tmp2 = userRegion[0].Name;
    alert(tmp);//undefined
    alert(tmp2);//undefined
}

What am I doing wrong? thanks.

EDIT: When I am debugging the javascript, I notice that '@Model.getJson()'; gets converted to a weird string that CANNOT be parsed by JSON.parse without an exception.

 var userRegion = JSON.parse('{"Name":"matt","Path":"c:/adsgadsg/sdagdsag"}');

Causes the exception Uncaught SyntaxError: Unexpected token &

Upvotes: 1

Views: 1165

Answers (3)

Zoltán Tamási
Zoltán Tamási

Reputation: 12764

You should first parse the JSON string to a Javascript object. This can be safely done for example with the Json2 library.

UPDATE: Also, you should use the Html.Raw function to print out the JSON string, because other way it will be HTML encoded (quotation mark will become ", etc.).

Your code should look like this:

function test() {
    var userRegion = JSON.parse('@Html.Raw(Model.getJson())');
    var tmp = userRegion.Name;
    //var tmp2 = userRegion[0].Name; this one is not correct
    alert(tmp);//undefined
    //alert(tmp2);//undefined
}

Upvotes: 1

user1634211
user1634211

Reputation:

I'm using the following in MVC3: var events = JsonConvert.DeserializeObject>(yourObject); Which will put the JSON string in the correct fields, and then I use a foreach loop to read from events, hope this will guide you in the correct direction.

Upvotes: 0

RredCat
RredCat

Reputation: 5421

I am pretty sure that alert(userRegion ); return undefined.

Json can't serialize method and you have to move this code in property inside your model class.

Upvotes: 0

Related Questions