In a Master Page I have the following markup
<body id="body" runat="server">
I have set runat="server"
because I need to be able to access the body element in code-behind.
I would now like to add a JavaScript function call to the body onload
event, like this:
<body id="body" runat="server" onload="someJavaScriptFunction();">
However, this is giving my a compile error, with a message of "Cannot resolve symbol someJavaScriptFunction();". If I run the application I get an error telling me
Compiler Error Message: CS1026: ) expected
What is going on here? onload
is a client-side event, so why does the ASP.NET compiler care about this?
You need to add this in the code behind;
protected void Page_Load(object sender, EventArgs e)
{
body.Attributes.Add("onload", "someJavaScriptFunction();");
}
Adding runat="server"
to a tag makes it a server tag, even if it isn't one of the explicitly prefixed ones (e.g. <asp:Panel />
). On server tags, any onXXXX
event handlers handle the server-side events, not the client-side events (except for when "client" is explicitly called out, such as with OnClientClick for buttons).
It is also an option to set:
<head>
<script language="text/javascript">
window.onload = function() { someJavaScriptFunction(); }
</script>
</head>
This is happening because ASP is trying to interpret the script inside the body tag as part of the code in the page. As though it were C# / VB...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With