How do I access ViewBag from JS
Asked Answered
N

7

40

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();
Newcastle answered 4/4, 2012 at 9:2 Comment(0)
G
78

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>
Grosgrain answered 4/4, 2012 at 9:6 Comment(4)
Why the @ before the <script> ?Felicitasfelicitate
Minus the @ symbol before Script, and this is the correct answer. ThanksNewcastle
you need the @ sign when using traditional <script> tags, just testedWainscoting
@Grosgrain this is very helpful. +1Bickford
C
15

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

Carpospore answered 4/4, 2012 at 9:8 Comment(2)
@Doomsknight. And I hope you won't use it.Felicitasfelicitate
Well in that case, check the value of ViewBag.CC server side, you might not be setting it in some case.Carpospore
C
9
<script type="text/javascript">
      $(document).ready(function() {
                showWarning('@ViewBag.Message');
      });

</script>

You can use ViewBag.PropertyName in javascript like this.

Chatter answered 4/4, 2012 at 9:6 Comment(2)
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.Newcastle
I was using this code, it calls just alert and it works fine. you can change alert('@ViewBag.Message'); it will work.Chatter
F
5

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.

Felicitasfelicitate answered 4/4, 2012 at 9:4 Comment(5)
I think you have an additional bracket? Ive tried similar to this but with ".Newcastle
@Doomsknight. ' or " is the same thing. Well Did it work?Felicitasfelicitate
On run time i see var c = $('#' + '2').val();Newcastle
@Doomsknight. O.k. So it's working... :) You have 2 in the ViewBag.CCFelicitasfelicitate
Seeing the 2 now, Ive gone back to var c = '@ViewBag.CC'; seems to be working now :/ Maybe running a few methods together were breaking it all. ThanksNewcastle
L
5

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();
Lipcombe answered 10/1, 2017 at 12:10 Comment(3)
I guess the javascript alternative might help others +1. Also i think you can just write '#@(ViewBag.CC)'Newcastle
Yeah, you can be right @Doomsknight, because world consisting multiple solutions :-)Lipcombe
yes @Doomsknight, You're right. I was just try to elaborate is an easy way. ;-)Lipcombe
W
0

Try this:

Anywhere in HTML: <input hidden [email protected] id="CC_id" />

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

Witte answered 4/4, 2012 at 9:2 Comment(0)
D
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"]';
Didache answered 20/10, 2021 at 20:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.