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