i using asp mvc , returning json object view, , cannot seem access of properties in json. here code.
in model have:
public string getjson() { file = 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 javascript have:
function test() { var userregion = '@model.getjson()'; var tmp = userregion.name; var tmp2 = userregion[0].name; alert(tmp);//undefined alert(tmp2);//undefined }
what doing wrong? thanks.
edit: when debugging javascript, notice '@model.getjson()'; gets converted weird string cannot parsed json.parse without exception.
var userregion = json.parse('{"name":"matt","path":"c:/adsgadsg/sdagdsag"}');
causes exception uncaught syntaxerror: unexpected token &
you should first parse json string javascript object. can safely done example json2 library.
update: also, should use html.raw
function print out json string, because other way html encoded (quotation mark become ", etc.).
your code should this:
function test() { var userregion = json.parse('@html.raw(model.getjson())'); var tmp = userregion.name; //var tmp2 = userregion[0].name; 1 not correct alert(tmp);//undefined //alert(tmp2);//undefined }
Comments
Post a Comment