Embedding ASP.Net code in external javascript files
I have code like
var mySession = "<%= Session["MyID"] %>"; alert ( mySession ); and when I put this code on my aspx page inside the script tag, it works fine. But it does not work in an external js file. I can not understand the problem.
Is there something wrong in my code, or does it look like this by default?
Thanks in advance
Server-side scripts ( <%= %> ) are evaluated only inside aspx pages. External javascript are static files. To achieve what you are looking for, you may need to declare a global js variable inside your aspx file:
var mySession = "<%= Session["MyID"] %>"; and use it in external js:
alert(mySession); Another option is to use AJAX. Configure the server side of the script, which will return the required session value and call this script from an external js file.
Darinβs suggestion is best, but if for some reason you donβt want to use the agreement to transfer data to your external js code using the variables defined on the aspx page, you can actually make your external js file aspx page. For example, you can name it "External.js.aspx" and set ContentType = "text / javascript" in the @Page directive. Then you can do whatever you expect from ASP.NET from within the javascript source.
However, serving aspx pages is much more expensive than using IIS for a static file. If this does not bother you, then this method can provide a more convenient and faster approach.