4

I am trying to pass data from the ViewBag object to javascript on my view.

//In the controller

ViewBag.SomeUrl = "http://mydomain.com";

//In the View

<script type="text/javascript">
  var theUrl = " @ViewBag.SomeUrl + ";
</script>

The problem I am having is that the following example sets the js var "theUrl" to:

" + http://mydomain.com + "

Omitting the concatenated quotes causes javascript to bark about the colons obviously. So how can I pass this url as a sting to my javascript var?

Thanks!

2 Answers 2

7

Why don't you simply output the string like this:

<script type="text/javascript">
  var theUrl = "@ViewBag.SomeUrl";
</script>

The + is not run on the server so you do not need it. The quotes shouldn't cause any issue with getting the value from the ViewBag.

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

Comments

0

You ARE passing it as a string to your javascript var. I don't understand what your complaint is. It's doing exactly what you seem to be wanting it to do.

If your complaint is about the pluses, then remove them from the string.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.