rahul
rahul

Reputation: 187030

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?

Upvotes: 4

Views: 5676

Answers (3)

fredrik
fredrik

Reputation: 17617

A nice way is to add all the values you need in the external Js files is to have an input type="hidden" for every value you need from aspx => js.

And on javascript window onload have a method that finds all you input fields and store them in an JS object.

Upvotes: 0

G-Wiz
G-Wiz

Reputation: 7426

Darin's suggestion is best, but if for someone reason you don't want to use the convention of passing data into your external js code by means of variables defined on the aspx page, you could actually make your external js file an aspx page. For example, you could name it "External.js.aspx" and set ContentType="text/javascript" in the @Page directive. Then you can do everything you expect to be able to do with ASP.NET from inside the javascript source.

However, serving aspx pages is much more computationally expensive than having IIS serve a static file. If that is not a concern for you, then this technique could provide a more maintainable and rapid approach.

Upvotes: 4

Darin Dimitrov
Darin Dimitrov

Reputation: 1038740

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.

Upvotes: 4

Related Questions