Warm tip: This article is reproduced from serverfault.com, please click

How do I access ViewBag from JS

发布于 2012-04-04 09:02:32

My attempted methods.

Looking at the JS via browser, the @ViewBag.CC is just blank... (missing)

        var c = "#" + "@ViewBag.CC";
        var d = $("#" + "@ViewBag.CC").value;
        var e = $("#" + "@ViewBag.CC").val();

        var c = "@ViewBag.CC";
        var d = $("@ViewBag.CC").value;
        var e = $("@ViewBag.CC").val();
Questioner
IAmGroot
Viewed
0
amd 2016-09-30 22:20:27

if you are using razor engine template then do the following

in your view write :

<script> var myJsVariable = '@ViewBag.MyVariable' </script>

UPDATE: A more appropriate approach is to define a set of configuration on the master layout for example, base url, facebook API Key, Amazon S3 base URL, etc ...```

<head>
 <script>
   var AppConfig = @Html.Raw(Json.Encode(new {
    baseUrl: Url.Content("~"),
    fbApi: "get it from db",
    awsUrl: "get it from db"
   }));
 </script>
</head>

And you can use it in your JavaScript code as follow:

<script>
  myProduct.fullUrl = AppConfig.awsUrl + myProduct.path;
  alert(myProduct.fullUrl);
</script>