Access ViewBag in JS file - Asp.net MVC

I have one Viewbag. I populated this viewbag value from the server side in the action result method. I need to access this Viewbag value in a Js file. I have access to this Viewbag on the .cshl page. Here is a sample code,

Var objMode = '@ViewBag.Mode'; // Written on the * .cshtml page.

but I need to access this value, for example, in the * .js syntax.

Thank you Nirav Paris

+4
source share
2 answers

You can not. You can write the ViewBag value in hidden input and then read it from the js file:

 <input type="hidden" value="@ViewBag.Mode" id="mode" /> 

Js file:

 var mode = document.getElementById('mode').value; 

EDIT . Another option:

 <script src="..." type="text/javascript" onload="InitMyScript('@ViewBag.Mode')"></script> 

Js file:

 function InitMyScript(mode){ //other code here } 
+7
source

You cannot reference ViewBag or other context elements in the included script files, since they are served as static files and are not processed on the server (if you need this, you can get around this by showing a view with JavaScript content type).

You need to put the value in your view as a JS variable:

 <script type="text/javascript"> // the object is only required if you want a nice syntax for multiple values. if (!window.ViewBag) window.ViewBag = {}; window.ViewBag.Mode = @Html.Raw(Json.Encode(this.ViewBag.Mode)); </script> 

Now you can refer to it in the script file.

+4
source

All Articles