Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access ViewBag in JS file - Asp.net MVC

I have one Viewbag. I have fill that viewbag value from server side in Action result method. I need to access this Viewbag value in Js file. I have access this Viewbag in *.cshl page properly. Here below shown my sample code,

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

but i need to access this value like above syntax in *.js file.

Thanks, Nirav Parikh

like image 499
KCS Nirav Avatar asked Dec 16 '22 12:12

KCS Nirav


1 Answers

You can't. You can write ViewBag value in hidden input and then read it from 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
}
like image 188
karaxuna Avatar answered Dec 28 '22 23:12

karaxuna