0

I have the following Action method.

public ActionResult Action()
{
   var model = new SampleViewModel();
   model.JsonString = ReadJsonStringFromSomewhere();
   return ViewResult(model);
}

In my view I have the following method to initialize a javascript variable.

<script type="text/javascript">

    var jsObject = eval("(" + <%= Model.JsonString %> + ")");
    alert(jsObject); 

</script> 

The 'jsObject' I get is undefined. What is wrong here. Also is it the best method to initialize a javascript variable with a complex json string?

3 Answers 3

3

JSON is literal JavaScript. You don't need the eval at all. The following will work:

<script type="text/javascript">

    var jsObject = <%= Model.JsonString %>;
    alert(jsObject); 

</script> 

That said, your eval version should still work, albeit more slowly. You don't show your JSON, but it might not be valid.

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

Comments

1

try this

<script type="text/javascript">

var jsObject = '<%= Model.JsonString %>';
alert(jsObject); 

1 Comment

No, that gives a string, not an object. He wants an object.
1

I think that looking at the rendered HTML and FireBug could be your best friend. The code snippet provided by Craig Stuntz looks good, so if it's not working, I would think that the emitted JSON has something wrong with it.

1 Comment

I'll say! Your reputation is almost 2k times that of mine! ;) But honestly, it seems like the most often forgotten "debugging" technique. I'm constantly reminding coworkers to do that.

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.