2012-01-18 48 views
3

我想從ViewBag對象傳遞數據到我的視圖上的JavaScript。MVC 3 - 將ViewBag內容分配給Javascript字符串

//In the controller 

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

//In the View 

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

我遇到的問題是,下面的例子中,JS VAR 「theUrl」 設置爲:

「+ http://mydomain.com +」

省略級聯引號引起JavaScript來明顯地冒着冒險。那麼我怎麼能通過這個URL作爲我的JavaScript var的刺痛?

謝謝!

回答

5

爲什麼你不只是輸出字符串是這樣的:

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

+沒有在服務器上運行,所以你並不需要它。引號不應該導致從ViewBag獲取值的任何問題。

+0

Doh .. cause Im a dork。謝啦 – Nick 2012-01-18 23:48:12

0

您將它作爲字符串傳遞給您的javascript var。我不明白你的投訴是什麼。它正在做你想要的事情。

如果您的投訴是關於這些優勢的,請將它們從字符串中刪除。