0
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?!!!

1
  • "{"id":"1","name":"stackoverflow","count":25}" it is not in the correct format , The count should be "count":"25". Commented Oct 22, 2013 at 11:07

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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))');

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.