john
john

Reputation: 801

How to modify or display JSON object using jquery and mvc Model

var dataToSend = '@Html.Raw(Json.Encode(Model.PageInput))';

my dataToSend contains below data :

"{"id":"1","name":"stackoverflow","count":25}"

How can I access the data?

I've tried the following :

alert(dataToSend.id)

or

alert(dataToSend[0].id)

or

alert(dataToSend[1].id)

All outputs: undefined

doesn't working. But why?!!!

Upvotes: 0

Views: 205

Answers (2)

Qpirate
Qpirate

Reputation: 2078

your dataToSend is a string, therefore it wont be availible,

you could try

var dataToSend = @Html.Raw(Json.Encode(Model.PageInput));

as the result will be rendered as JSON before it gets to the client.

or you could use the JSON library and do

var dataToSend = JSON.parse('@Html.Raw(Json.Encode(Model.PageInput))');

Upvotes: 1

geevee
geevee

Reputation: 5451

replace:

var dataToSend = '@Html.Raw(Json.Encode(Model.PageInput))';

with:

var dataToSend = @Html.Raw(Json.Encode(Model.PageInput));

(it should be an object, not a string)

and then try:

dataToSend.name

P.S:

you can also parse strings into json with javascript.

string > json:

var obj = JSON.parse(str);

json > string:

var str = JSON.stringify(obj);

hope that helps.

Upvotes: 2

Related Questions