MVC 3 - 将ViewBag内容分配给Javascript字符串

Nic*_*ick 3 c# asp.net-mvc-3

我试图将ViewBag对象中的数据传递给我的视图中的javascript.

//In the controller

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

//In the View

<script type="text/javascript">
  var theUrl = " @ViewBag.SomeUrl + ";
</script>
Run Code Online (Sandbox Code Playgroud)

我遇到的问题是以下示例将js var"theUrl"设置为:

"+ http://mydomain.com +"

省略连接的引号会导致javascript显然对冒号大加吠叫.那么如何将这个url作为sting传递给我的javascript var?

谢谢!

Joh*_*rer 6

为什么不简单地输出这样的字符串:

<script type="text/javascript">
  var theUrl = "@ViewBag.SomeUrl";
</script>
Run Code Online (Sandbox Code Playgroud)

+所以你不需要它是不是在服务器上运行.引号不应该导致从ViewBag获取值的任何问题.