user3501278 user3501278 -4 years ago 149
C# Question

How to access Global.asax variables in Javascript

I am unsuccessful in accessing application state variable in javascript.

I declared the app state variable as,

Application["MYVAR"] ="My Variable";


JS:

var _myjsvar = <%='Application["MYVAR"]'%>
alert(_myjsvar);


But I don't get the value in JS alert. Any help, appreciated.

Answer Source

This should work as long as it is in a page executed by server ( ex :your aspx view etc..)

var _myjsvar = '<%= Application["MYVAR"] %>';
alert(_myjsvar);

If it is a razor view where you want to access the Application variable, you can do this.

<script>
    var _myjsvar = "@HttpContext.Current.Application["MYVAR"]";
    alert(_myjsvar);
</script>
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download