Amitabh
Amitabh

Reputation: 61287

How to initialize a javascript variable using Json String in Asp.net MVC?

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?

Upvotes: 0

Views: 1633

Answers (3)

Andorbal
Andorbal

Reputation: 880

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.

Upvotes: 1

Craig Stuntz
Craig Stuntz

Reputation: 126587

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.

Upvotes: 3

Akyegane
Akyegane

Reputation: 905

try this

<script type="text/javascript">

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

Upvotes: 1

Related Questions