Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

body runat="server" causing compilation error

Tags:

asp.net

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?

like image 720
Richard Ev Avatar asked Apr 07 '09 13:04

Richard Ev


2 Answers

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

like image 109
Dead account Avatar answered Oct 21 '22 04:10

Dead account


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

like image 27
John Gietzen Avatar answered Oct 21 '22 04:10

John Gietzen