Reputation: 801
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
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
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