开发者

Embedding ASP.Net code in external javascript files

开发者 https://www.devze.com 2022-12-22 01:31 出处:网络
I have 开发者_开发问答a code like var mySession = \"<%= Session[\"MyID\"] %>\"; alert ( mySession );

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?


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.


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号