MVC无法在javascript中为j变量创建json字符串 [英] MVC failed to make a json string in view for a variable in javascript

查看:86
本文介绍了MVC无法在javascript中为j变量创建json字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在视图中有一个json变量,如下所示:

I have a json variable in the view as follows:

 @{
        string jsontemp = '{"Cars": {"Nissan": [{"Model": "Sentra", "doors": 4},{"Model": "Maxima", "doors": 4}],"Ford": [{"Model": "Taurus", "doors": 4},{"Model": "Escort", "doors": 4}]}}';
}

我想将其分配给javascript中的变量。

I want to assign it to a variable in javascript.

<script>
var jsondata = @jsontemp;

var arraydata = JSON.parse(jsondata);

</script>

但我收到以下错误消息:

But I get the following error message:

Uncaught SyntaxError:意外的令牌&

Uncaught SyntaxError: Unexpected token &

我明白当视图运行时,我的json变量来自以下格式: [福特,宝马,菲亚特] 转换为 [& quot;福特& quot;, & quot;宝马& quot;,& quot;菲亚特& quot;]

I understand that when the view is run, my json variable is from the format: ["Ford", "BMW", "Fiat"] convert to [&quot;Ford&quot;, &quot;BMW&quot;, &quot;Fiat&quot;]

我想从视图中检索json字符串,并将其分配给脚本代码中的变量,然后我从该字符串解析到数组。

I want to retrieve the json string from view, and assign it to a variable in the script code, then I parse from that string to the array.

推荐答案

你需要使用 @ Html.Raw()以原始形式输出数据。

You need to use @Html.Raw() to output the data in raw form.

否则 @ 将通过HtmlEncoding来转义输出。

Otherwise @ will escape your output by HtmlEncoding it.

<script>
    var jsondata = @Html.Raw(jsontemp);
    var arraydata = JSON.parse(jsondata);

</script>

这篇关于MVC无法在javascript中为j变量创建json字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆