views:

331

answers:

5

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

+1  A: 

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.

jball
+1  A: 

Visual Studio is validating the HTML markup on the page. Strictly speaking, the '<' is not valid XHTML. This warning may be caused by a limitation of the validation as Visual Studio is interpreting the '<' character inside javascript as meaning 'less than'!

Obviously these inline expressions are not valid client code. One can change the HTML validation options in Tools|Options|Text Editor|HTML. Mind you, it may be better to simply ignore these warnings rather validate against HTML 4.01 or turn off the validation completely.

Tom
+2  A: 

If all you're doing is adding javascript to your page, you could use RegisterClientScriptBlock to build the script server-side and then let it output it to the page.

This way you don't have to have any server-side scripting within your page and all the overhead that goes with that.

CAbbott
+1  A: 

I've done this before and not had problems. However, I use jQuery's $(document).ready() instead of init(). I don't think that should be an issue, though.

What datatype is x? If it is a string, try wrapping it in single quotes, and if it's a number use the parse function for that datatype.

<script type="text/javascript" language="javascript">
var s;
var n;
function init()
{
     s = '<%= x %>';
     n = parseInt('<%= x %>');
     eval('<%= x %>'); /* Raw Javascript */
}
</script>

Another issue would be the access level of the property. ASP.NET web forms can't access private fields directly from the code-behind. Access has to be protected or public.

Eval Javascript Function

Jim Schubert
The string contains raw JavaScript code, which I want to execute.
Joel Spolsky
then you can also use eval('string');
Jim Schubert
+2  A: 

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

RickNZ