Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I access ViewBag from JS

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(); 
like image 966
IAmGroot Avatar asked Apr 04 '12 09:04

IAmGroot


People also ask

Can you access ViewBag from JavaScript?

The ViewBag object value will be set inside Controller and then the value of the ViewBag object will be accessed inside JavaScript function using Razor syntax in ASP.Net MVC Razor.

How do I get ViewBag data on my controller?

To pass the strongly typed data from Controller to View using ViewBag, we have to make a model class then populate its properties with some data and then pass that data to ViewBag with the help of a property. And then in the View, we can access the data of model class by using ViewBag with the pre-defined property.

How do you check if the ViewBag value is null or not?

using @ViewBag. Property!= null should be fine.

How do you get the ViewBag value in Ajax success?

What i would suggest is to create a hidden field inside your partial view's cshtml file and assign that the value of ViewBag property at compile time. Then inside success function get the value of hidden field and compare.


2 Answers

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> 
like image 118
amd Avatar answered Sep 30 '22 03:09

amd


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

like image 27
ZeNo Avatar answered Sep 30 '22 03:09

ZeNo