Skip to content Skip to sidebar Skip to footer

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?

Solution 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:

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

Solution 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:

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

Solution 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

<scripttype="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

Solution 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.

Post a Comment for "Using Asp.net Tags In A .js File?"