Tuesday, 15 September 2015

javascript - Passing (and parsing!) JSON objects through MVC4 -



javascript - Passing (and parsing!) JSON objects through MVC4 -

i'm confused how should using json objects within mvc , how should passed controller, view, jscript.

i'm not sure if i'm correctly parsing json objects @ right points...

my controller returning partialview json object ("variables" list of info e.g. id=2012, name=billyjoel, value="£2,000"):

public actionresult javascriptconstants() { var variables = service.obtain<variableservice>().all().tolist(); var json = new javascriptserializer().serialize(variables); homecoming partialview("javascriptconstants", json); }

my view makes info available scripts creating variable:

@model string ... var mvclistofvariablesindb = '@html.raw(json.encode(model))';

my jscript file accesses info , attempts pull out info , key value pairs, seems interpreting json string:

var variablelist = $.parsejson(mvclistofvariablesindb); (var variable in variablelist) { alert(variablelist[variable]); }

this returns alerts of ", [, {, etc. each character of string displayed. how access key values of json object?

i've tried changing js use:

var variablelist = $.parsejson(mvclistofvariablesindb);

but gives me uncaught syntaxerror: unexpected token i error in browser (i'm assuming when hits "i" of "id).

any help much appreciated, thanks.

i found issue:

the issue utilize of javascriptserializer().serialize(foo) creating json object contained newlines , tabs instead of replacing them \n , \t.

$.parsejson() cannot handle newlines , throws unexpected token error.

this corrected importing json.net bundle , using :

var json = jsonconvert.serializeobject(variables);

this passed json object newlines , tabs replaced \n's , \t's. can made accessible view using:

@model string ... var mvclistofvariablesindb = '@html.raw(json.encode(model))';

and in script using:

var variablelist = $.parsejson(mvclistofvariablesindb)

hope helps else 1 day...

javascript asp.net-mvc json

No comments:

Post a Comment