Visual Studio“条件编译已关闭";传递JSON对象时视图中的错误 [英] Visual Studio "Conditiional compilation is turned off" Error In View When Passing JSON Object

查看:97
本文介绍了Visual Studio“条件编译已关闭";传递JSON对象时视图中的错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在通过ViewBag将JSON对象传递给Javascript,并在视图中添加以下代码:

I'm passing a JSON object to Javascript via the ViewBag with the following code in my view:

var jsonResultData = @Html.Raw(ViewBag.JsonResultData);

这种方法效果很好,但是VisualStudio不断向我发出有条件的编译已关闭"警告.似乎VS想要@ Html.Raw(ViewBag.JsonResultData)周围的引号;如果添加引号,jQuery会将变量视为字符串而不是JSON数据.

This approach works fine but VisualStudio keeps giving me a 'Conditional compilation is turned off' warning. It seems VS wants quotes around @Html.Raw(ViewBag.JsonResultData); If I add quotes jQuery sees the variable as a string rather than JSON data.

我的方法有缺陷吗?我还有其他方法可以解决这个问题吗?如果不能,我可以禁用VS警告吗?该警告的一个令人讨厌的副作用是我无法使用CTRL K-D格式化我的代码.

Is my approach flawed? Is there another way I should be approaching this? If not can I disable the VS warning? An annoying side effect of the warning is I can't format my code using CTRL K-D.

推荐答案

为什么要使用ViewBag?我想在您的控制器操作中,您已将某些模型手动序列化为JSON,不是吗?像这样:

Why are you using ViewBag? I suppose in your controller action you have manually serialized some model into JSON, haven't you? Something like this:

public ActionResult Foo()
{
    var model = ...
    ViewBag.JsonResultData = new JavaScriptSerializer().Serialize(model);
    return View(model);
}

我不建议您这样做.而是这样做:

I wouldn't recommend you doing this. Instead do this:

public ActionResult Foo()
{
    var model = ...
    return View(model);
}

并在您看来:

<script type="text/javascript">
    var jsonResultData = @Html.Raw(Json.Encode(Model));
</script>

就警告而言,Razor Intellisense远非完美.您确实可能会得到一些警告,尤其是在将剃须刀与javascript混合使用时.我们只能希望他们会在ASP.NET MVC的未来版本中解决此问题.目前,请忽略这些警告.老实说,当我使用视图时,我不再在Visual Studio中查看警告或错误,因为我事先知道它们是错误的,并且我的应用程序在运行时运行良好.

As far as the warning is concerned, well, Razor Intellisense is far from perfect. You might indeed get some warnings especially when you mix razor with javascript. We can only hope they will fix this in future versions of ASP.NET MVC. For the moment ignore those warnings. To be honest when I am working with a view I no longer look at warnings or error in Visual Studio as I know in advance that they are buggy and my application works perfectly fine when run.

这篇关于Visual Studio“条件编译已关闭";传递JSON对象时视图中的错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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