Using ASP.Net tags in a .js file?

Is it possible to embed <% ... %> tags in a javascript file and have it render the appropriate server-side code? How can this be done?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

The process is actually backwards from what you’re thinking.

You create an *.aspx page that renders to a JavaScript file. You can then reference that *.aspx page in your <script> tag:

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

Method 2

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

In your page, to refrence it you would do:

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

Method 3

I’m going to make some assumptions on what you are trying to accomplish. Most likely you have a javascript file that needs access to some info on the server. Let’s say you need some stuff from the session that if it were an aspx page you’d make it look something like

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

obviously this won’t work in a .js file since it never goes through the page lifecycle that an aspx page would be processed though. However, you don’t need to transform your entire .js file into an .aspx page as some others might be suggesting. There are lots of other ways to expose that data to your js code. I’ll list 2.

  1. emit the above <script> in your page response (perhaps using a <asp:ContentPlaceHolder />)
  2. create a webservice (could even be a simple .ashx) that returns the var username = ... or even better returns json

Method 4

Yes, it’s possible by simply making a regular web page that contains Javascript instead.

However, it might not behave like you expect. Javascript files are cached longer than pages. As the browser might not request the file from the server each time, your could would not be executed each time the file is used.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x