0

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.

1

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.