我能够重现您的问题并找到解决方案。至于为什么这个解决方案有效,我不能说,但以下是我遵循的步骤。
1.从一个新的 MVC 4 项目(基本)中,我创建了一个具有以下标记的视图(注意 ReSharper 7 没有抱怨)
@{
ViewBag.Title = "Index";
ViewBag.Array = new string[] {"apples", "oranges", "bananas"};
}
<script type="text/javascript">
var stuff = "! @Html.Raw(Json.Encode(ViewBag.Array))";
alert(stuff);
</script>
<h2>Index</h2>
2.编译并运行应用程序,收到以下错误:CS0103: The name 'Json' does not exist in the current context
.
3.尝试在View中导入命名空间,将程序集添加到Views web.config中,确保在项目中正确引用。这些都没有效果。
4.解决方案添加了以下行(<assemblies>
<add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
)到编译部分中的 web.config(主要 web.config,而不是 Views 文件夹)
<system.web>
<httpRuntime targetFramework="4.5" />
<compilation debug="true" targetFramework="4.5">
<!--Add the following. Ensure compilation is not self closing,
it was on mine-->
<assemblies>
<add assembly="System.Web.Helpers, Version=2.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
</assemblies>
</compilation>
5.重新编译,这是生成的 HTML 页面输出,没有错误
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link href="/Content/site.css" rel="stylesheet"/>
<script src="/Scripts/modernizr-2.6.2.js"></script>
</head>
<body>
<script type="text/javascript">
var stuff = "! ["apples","oranges","bananas"]";
alert(stuff);
</script>
<h2>Index</h2>
<script src="/Scripts/jquery-1.8.2.js"></script>
</body>
</html>