可以从Javascript文件访问MVC ViewBag对象吗? [英] Possible to access MVC ViewBag object from Javascript file?

查看:639
本文介绍了可以从Javascript文件访问MVC ViewBag对象吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能做在MVC应用程序的JavaScript文件下面?

  $(函数(){
   警报(@ ViewBag.someValue);
}

目前它抛出的错误:


  

引用未定义的XML名称@ViewBag



解决方案

我不相信有任何目前的方式来做到这一点。剃刀引擎并不解析JavaScript文件,只有剃刀的意见。然而,你可以完成你想要的东西通过设置的Razor视图里面的变量:

 <脚本>
  VAR someStringValue ='@(ViewBag.someStringValue)';
  VAR someNumericValue = @(ViewBag.someNumericValue);
< / SCRIPT>
< - !someStringValue和someNumericValue将在脚本中可用 - >
<脚本SRC =JS / myscript.js>< / SCRIPT>

乔在评论中指出,该字符串值以上将打破,如果有中有一个单引号。如果你想使这个完全铁证如山,你就必须更换所有单引号与转义单引号。问题存在,所有的突然斜线的成为一个问题。例如,如果你的字符串是富\\'栏,并更换了单引号,有什么会出来是 foo的\\\\酒吧,你就马上回了同样的问题。 (这就是链式编码的古老的困难。)来处理这种情况的最好办法是把反斜线以及行情特殊,并确保他们的所有转义:

  @ {
      VAR safeStringValue = ViewBag.someStringValue
          .Replace(\\\\,\\\\\\\\)
          .Replace(',\\\\');
  }
  VAR someStringValue ='@(safeStringValue)';

Is it possible to do the following from a javascript file in an MVC application?

$(function(){
   alert(@ViewBag.someValue);
}

Currently it throws the error:

reference to undefined XML name @ViewBag

解决方案

I don't believe there's currently any way to do this. The Razor engine does not parse Javascript files, only Razor views. However, you can accomplish what you want by setting the variables inside your Razor view:

<script>
  var someStringValue = '@(ViewBag.someStringValue)';
  var someNumericValue = @(ViewBag.someNumericValue);
</script>
<!-- "someStringValue" and "someNumericValue" will be available in script -->
<script src="js/myscript.js"></script>

As Joe points out in the comments, the string value above will break if there's a single quote in it. If you want to make this completely iron-clad, you'll have to replace all single quotes with escaped single quotes. The problem there is that all of the sudden slashes become an issue. For example, if your string is "foo \' bar", and you replace the single quote, what will come out is "foo \\' bar", and you're right back to the same problem. (This is the age old difficulty of chained encoding.) The best way to handle this is to treat backslashes and quotes as special and make sure they're all escaped:

  @{
      var safeStringValue = ViewBag.someStringValue
          .Replace("\\", "\\\\")
          .Replace("'", "\\');
  }
  var someStringValue = '@(safeStringValue)';

这篇关于可以从Javascript文件访问MVC ViewBag对象吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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