Using MVC / Razor ViewBag variables in JavaScript

I needed to dynamically populate an iframe “src” property with a URL passed from a controller action. I was going to set the value using JavaScript inside the view.

In my controller, I pass in a parameter to determine which URL should be generated and assign it to a ViewBag property:


public ActionResult DoStuff(string action) {
           switch (action) {
                case "all":
                    ViewBag.Url = "";
                case "new":
                    ViewBag.Url = "";

Now we delve into the view. First, I have an iframe declared.


The JavaScript to populate the iframe is straight forward. The trickiness to pull in the ViewBag variable to use it in JavaScript is this: Enclose the Razor code inside a <text> element. Remember to declare the variable outside of that block:

    var url;
            url = '@ViewBag.Url';
    document.getElementById('contentSource').src = url;

Note, however, that the URL returned has encoded the “&” as “&amp;”, and in my case, this caused my URL to malfunction. A simple string replace fixed it, but just be aware of it.

url = url.replace('&amp;', '&');

, ,

  1. Leave a comment

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: