tags:

views:

623

answers:

2

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?

+5  A: 

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

Dead account
OK, I can see how that would work - but why does adding runat="server" mean I need to use this approach?
Richard Ev
I think because it's looking for the Body_SomeJavaScriptFunction method in the code behind, because you told it to "run at server" ?
Dead account
Correct... I appended your answer Ian, hope you don't mind :)
Daniel Schaffer
No problem. I've hit my 200 rep points for the day so I guess I better get on with some work :)
Dead account
Well appended Daniel, thanks!
Richard Ev
+3  A: 

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...

John Gietzen
This doesn't answer the questions "What is going on here?" and "why does the ASP.NET compiler care about this?"
Cerebrus
This is the approach that I went with in the end, in my scenario.
Richard Ev