最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Visual Studio "Conditiional compilation is turned off" Error In View When Passing JSON Object - S

programmeradmin3浏览0评论

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

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

This approach works fine but VisualStudio keeps giving me a 'Conditional pilation 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.

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.

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

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

This approach works fine but VisualStudio keeps giving me a 'Conditional pilation 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.

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.

Share Improve this question edited May 28, 2011 at 23:43 Mark asked May 11, 2011 at 21:39 MarkMark 21.7k14 gold badges55 silver badges71 bronze badges 1
  • That's Javascript, not jQuery. – SLaks Commented May 11, 2011 at 21:44
Add a ment  | 

1 Answer 1

Reset to default 9

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 remend you doing this. Instead do this:

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

and in your view:

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

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.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论