Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"Expected expression" with <%=foo%> inside JavaScript in .aspx file

I've got code like this in an .aspx file:

<script type="text/javascript" language="javascript">
function init()
{
     <%= x %>
}

It works fine (x is a string that will be bound to some JavaScript at runtime), but when compiling I get an "Expected expression" warning on the <%=

I know it's not the nicest code in the world, but there are various historical bits of code that like to inject little bits of JavaScript into the page. All perfectly innocent :)

like image 437
Joel Spolsky Avatar asked Dec 14 '09 22:12

Joel Spolsky


2 Answers

The warning is happening because the code block is inside a JavaScript <script> block; the compiler is trying to be smart about recognizing the difference between HTML/controls and JavaScript.

Although it's a bit ugly, you should be able to eliminate the warning by using eval('<%= x %>')

You might also have a look at an article I wrote on using ASP.NET to create dynamic JavaScript: http://www.12titans.net/p/dynamic-javascript.aspx

like image 104
RickNZ Avatar answered Sep 19 '22 20:09

RickNZ


If you wanted to be perfectly legal, use a literal:

<asp:Literal ID="litX" runat="server"></asp:Literal>

and set its Text to the whole <script type="text/javascript" language="javascript">...</script> block on the server side.

like image 21
jball Avatar answered Sep 23 '22 20:09

jball