38

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();
IAmGroot
  • 13,760
  • 18
  • 84
  • 154

7 Answers7

75

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>
amd
  • 20,637
  • 6
  • 49
  • 67
14

try: var cc = @Html.Raw(Json.Encode(ViewBag.CC)

ZeNo
  • 1,648
  • 2
  • 15
  • 28
9
<script type="text/javascript">
      $(document).ready(function() {
                showWarning('@ViewBag.Message');
      });

</script>

You can use ViewBag.PropertyName in javascript like this.

adt
  • 4,320
  • 5
  • 35
  • 54
  • Im not sure wht showWarning does. (didnt do anything for me) but the rest did contain the correct value. So I saw `showWarning('2');` in my code. – IAmGroot Apr 04 '12 at 09:17
  • 1
    I was using this code, it calls just alert and it works fine. you can change alert('@ViewBag.Message'); it will work. – adt Apr 04 '12 at 09:20
4

ViewBag is server side code.
Javascript is client side code.

You can't really connect them.

You can do something like this:

var x = $('#' + '@(ViewBag.CC)').val();

But it will get parsed on the server, so you didn't really connect them.

gdoron
  • 147,333
  • 58
  • 291
  • 367
3

You can achieve the solution, by doing this:

JavaScript:

var myValue = document.getElementById("@(ViewBag.CC)").value;

or if you want to use jQuery, then:

jQuery

var myValue = $('#' + '@(ViewBag.CC)').val();
Arsman Ahmad
  • 2,000
  • 1
  • 26
  • 34
0

None of the existing solutions worked for me. Here's another solution I found that did work:

Controller:

TempData["SuccessMessage"] = "your message here";

View:

let msg = '@TempData["SuccessMessage"]';
0

Try this:

Anywhere in HTML: <input hidden value=@ViewBag.CC id="CC_id" />

In JS: var CC= document.getElementById("CC_id").value.toString();

Mahyar Mottaghi Zadeh
  • 1,178
  • 6
  • 18
  • 31
Ali Raji
  • 41
  • 2