Body runat = "server" causing a compilation error
On the main page I have the following markup
<body id="body" runat="server"> I set runat="server" because I need to have access to the body element in the code.
Now I would like to add a JavaScript function call to the body onload , for example:
<body id="body" runat="server" onload="someJavaScriptFunction();"> However, this gives me a compilation error with the message "Cannot resolve the symbol someJavaScriptFunction ();". If I run the application, I get an error
Compiler Error Message: CS1026 :) expected
What's going on here? onload is a client-side event, so why does the ASP.NET compiler care about this?
You need to add this to the code behind;
protected void Page_Load(object sender, EventArgs e) { body.Attributes.Add("onload", "someJavaScriptFunction();"); } Adding runat="server" to the tag makes it a server tag, even if it is not one of the explicitly prefix ones (for example, <asp:Panel /> ). In server tags, any onXXXX event onXXXX process events on the server side, rather than events on the client side (except when explicitly calling the "client", for example, with OnClientClick buttons for buttons).
You can also install:
<head> <script language="text/javascript"> window.onload = function() { someJavaScriptFunction(); } </script> </head> This is because ASP is trying to interpret the script inside the body tag as part of the code on the page. Like it's C # / VB ...