Possible to access MVC ViewBag object from Javascript file?

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="https://stackoverflow.com/questions/10389649/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)";

Leave a Comment