Joe.wang
Joe.wang

Reputation: 11791

Asp.net inline expression wasn't outputed in the js file

All, If I add an inline expression in the aspx page like below.

<script type="text/javascript">
   var notAcceptError='<%= lblMessage%>';//the actually value is "test message"
</script>

As we know. There should exist a variable named lblMessage is defined in the code-behind file of aspx. in this way , everything is fine. But If I move the above code into a js file which is linked by the same page. the output of expression failed. seems the asp.net can't recognize this expression. I can't understand why this doesn't work in the linked external js file. In my understanding. writing in the aspx or an external js is the same. thanks.

Upvotes: 1

Views: 565

Answers (2)

Waqas Raja
Waqas Raja

Reputation: 10870

The asp.net inline expression only work in .aspx files. It will not work in .js file because .js files served as static files and are not parsed at runtime.

If you really want to use a variable value in code-bind file into the js you can do like this.

In your aspx file do this.

<script type="text/javascript">
   var notAcceptError = '<%= lblMessage%>'; //the actually value is "test message"
</script>

<%-- please note the external file is referenced after the javascript variable --%>
<script type="text/javascript" src="myjsfile.js">
</script>

And inside your myjsfile.js use the variable like this

alert(notAcceptError);

Upvotes: 3

Bernhard Hofmann
Bernhard Hofmann

Reputation: 10411

Your understanding is wrong. ASPX files are parsed and evaluated, whereas JS files are served from the server without any parsing or evaluation.

Upvotes: 2

Related Questions