开发者

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

I'm passing a JSON object to Javascript via the V开发者_运维技巧iewBag with the following code in my view:

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

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.

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.


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);
}

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜