Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Embedding ASP.Net code in external javascript files

I have a code like

var mySession = "<%= Session["MyID"] %>";
alert ( mySession );

and when I place this code in my aspx page inside a script tag, it works fine. But it doesn't work in an external js file. I am not able to figure out the problem.

Is there anything wrong in my code, or is it like this by default?

like image 848
rahul Avatar asked Feb 27 '23 11:02

rahul


1 Answers

Server side scripts (<%= %>) are evaluated only inside aspx pages. External javascript are static files. To achieve what you are looking for you might need to declare a global js variable inside your aspx file:

var mySession = "<%= Session["MyID"] %>";

and use it in your external js:

alert(mySession);

Another option is to use AJAX. Set up a server side script which will return the required session value and call this script from the external js file.

like image 139
Darin Dimitrov Avatar answered Mar 06 '23 18:03

Darin Dimitrov