3

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 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.

Mark
  • 21,067
  • 14
  • 53
  • 71

1 Answers1

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 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.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Darin, that's correct. I'm serializing the data in my controller. I'm using ViewBag as I'm just passing error strings. I'm not serializing the entire model. Why do you recommend encoding the data on the client with Json.Encode rather than doing it server side? – Mark May 11 '11 at 22:07
  • @Mark S., because I consider the usage of ViewBag/ViewData as bad practice in ASP.NET MVC. It is weakly typed, you get no Intellisense, you are relying on magic strings, your unit tests are extremely brittle to modifications, your code is not refactor friendly, ... And because you already have a controller action returning a strongly typed view model to the view why write additional meaningless code in this controller action? Why making this action fat when all you need is inside the model? And then in the view if you need to access it using javascript simply JSON serialize this model. – Darin Dimitrov May 11 '11 at 22:11