最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Embedding ASP.Net code in external javascript files - Stack Overflow

programmeradmin3浏览0评论

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?

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?

Share Improve this question edited Jun 25, 2018 at 7:25 Lundin 216k46 gold badges279 silver badges432 bronze badges asked Mar 4, 2010 at 6:31 rahulrahul 187k50 gold badges238 silver badges264 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 4

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 putationally 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)

  1. 暂无评论