Question

I have a one page that uses Javascript to load several PartialViews. I am trying to access ViewBag in some Javascript but am having problems.

MyView:

<div>
  <script>
    var test = @ViewBag.test;
    alert(test);
  </script>
</div>

The controller which handles this view:

public PartialViewResult MyView()
{
  ViewBag.test = "test";
  return PartialView();
}

When I run it, the Javascript alert does not appear. I get a "Conditional compilation is turned off" highlight under the View's calling of ViewBag.

Was it helpful?

Solution

When your view is rendered, this is what is produced:

var test = test;

..that is obviously not valid javascript.

You need to enclose it in quotes:

var test = "@ViewBag.test";

Which produces:

var test = "test";

..valid Javascript.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top