MVC 3-将ViewBag内容分配给Javascript字符串 [英] MVC 3 - Assign ViewBag Contents to Javascript string

查看:76
本文介绍了MVC 3-将ViewBag内容分配给Javascript字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试将数据从ViewBag对象传递到视图上的javascript.

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>

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

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

"+ http://mydomain.com +"

省略连接引号会使javascript明显冒号.那么如何将这个网址作为字符串传递给我的javascript var?

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?

谢谢!

推荐答案

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

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

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

+不在服务器上运行,因此您不需要它.引号不会对从ViewBag获取值造成任何问题.

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.

这篇关于MVC 3-将ViewBag内容分配给Javascript字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆