views:

30

answers:

3

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?

+1  A: 

try this

<script type="text/javascript">

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

Akyegane
No, that gives a string, not an object. He wants an object.
Craig Stuntz
+2  A: 

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.

Craig Stuntz
+1  A: 

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.

Andorbal
+1 for looking at the HTML. I should have mentioned that.
Craig Stuntz
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.
Andorbal