How to initialize a javascript variable using Json String in Asp.net MVC?
I have the following Acti开发者_Python百科on 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?
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.
try this
<script type="text/javascript">
var jsObject = '<%= Model.JsonString %>';
alert(jsObject);
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.
精彩评论