Using ASP.Net tags in a .js file?

Is it possible to embed <% ... %> tags in a javascript file and does it display the corresponding server code? How can I do that?

+6
source share
4 answers

The process is actually the opposite of what you think.

You create a * .aspx page that displays a JavaScript file. Then you can link to this * .aspx page in the <script> :

 <script type="text/javascript" src="someJavaScript.aspx"></script> 
+13
source

Yes, it is possible, but it will not be a JS file, it will be an aspx file with Javascript in it instead of html.

On your page, to confirm this, you must:

 <script type="text/javascript" src="myPage.aspx"></script> 
+6
source

Yes, it is possible just by creating a regular web page containing Javascript.

However, it may not behave as you expect. Javascript files are cached longer than pages. Since the browser cannot request a file from the server each time, your file cannot be executed every time the file is used.

+1
source

I am going to make some assumptions about what you are trying to fulfill. Most likely you have a javascript file that needs access to some information on the server. Let's say you need something from the session, that if it were an aspx page, you would look something like this:

 <script type="text/javascript"> var username = '<%= Session["username"] %>'; var account_num = '<%= Session["account_num"] %>'; </script> 

obviously this will not work in the .js file since it never goes through the life cycle of the page, which will be treated as an aspx page. However, you do not need to convert your entire .js file to an .aspx page, as some may suggest. There are many other ways to provide this data to your js code. I will list 2.

  • fix the above <script> in the response to your page (possibly using <asp:ContentPlaceHolder /> )
  • create a web service (maybe even a simple .ashx) that returns var username = ... or even better returns json
+1
source

Source: https://habr.com/ru/post/890639/


All Articles