MVC 3 - Assign ViewBag Contents to Javascript stri

2019-07-06 22:03发布

问题:

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!

回答1:

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.



回答2:

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.