C# code request: Using "if" "else" in a user control to write javascript into the body "onload" event

I have an admin system that uses "user controls" to provide the open head and body (header.ascx) and close body (footer.ascx) of the admin centre html pages.

So for each page I (currently) have something like:

<%@ Page language="c#" Codebehind="default.aspx.cs" AutoEventWireup="false" Inherits="admin._default" %>
<form id="mainForm" method="post" runat="server">
      Main Content Here

Each page references a class containing the code section below to load the header and footer controls at the start and end of the page respectively:

protected override void OnInit(System.EventArgs e)
    this.Controls.AddAt(0, LoadControl("Header.ascx"));

The header control currently looks like this:

<%@ Control Language="c#" AutoEventWireup="false" Codebehind="Header.ascx.cs" Inherits="admin.Header" TargetSchema="http://schemas.microsoft.com/intellisense/ie5"%>
<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
    <title>Admin Center</title>
    <meta name='robots' content='noindex,nofollow' ></head>

Here's the question:

I'm reworking an old ASP3 script that simply does this:

   show_what = "this_menu_option" 'Hard coded into the top of each main page (but could be passed in the QueryString
   If show_what <> "" Then
     Response.Write("<body onload=""MM_showHideLayers('" & show_what & "','','show')"">")
   End If

So currently the Header.ascx control includes the <body> tag, so how would I get the Header.ascx to pickup on the "show_what" variable and replicate the code output as shown above in the ASP 3 example (this time in C#)?

Many thanks.
Who is Participating?

Is this what you are after?

   string show_what = "this_menu_option"; //Hard coded into the top of each main page (but could be passed in the QueryString
   if (show_what != ""){
     Response.Write("<body onload=""MM_showHideLayers('" + show_what + "','','show')"">");
   } else {


or you can do it in code by gaining a reference to the body tag and simply adding an attribute.
Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

w3digitalAuthor Commented:
Thanks Len,

Acutally no, I don't think that is what I am after as I will need to specific on a page by page basis which javascript menu option I wish to call from the body onload event handler. So the "show_what" variable will be specified in ... say ... the default.aspx.cs.

Then the header.aspx should output the code:

                               <body onload="MM_showHideLayers('main','','show')">

I did try something like the code you have submitted above and got the following error:

The name 'show_what' does not exist in the class or namespace 'ASP.Header_ascx'

I was thinking something like this (but that works...)

                              // CODE behind default.aspx.cs

            private void Page_Load(object sender, System.EventArgs e)
                                                show_what = "admin_menu"; // put here for example only
                  if (show_what != "")
                        // below code is rubbish but the sort of thing I need to programmatically add
                        // an onload attribute to <body> tag on a page by page basis
                        Body.Attributes["onload"] = "MM_showHideLayers('" + show_what + "','','show')";
w3digitalAuthor Commented:
Ah, I just saw gregoryyoung's comment after submitting my thoughts.

That's what I'm after.

gregoryyoung, can you provide a code sample please?
w3digitalAuthor Commented:
Thanks gregoryyoung,

I reckon I'm almost there but am doing something wrong.

Here's the Page_Load code:

                                private void Page_Load(object sender, System.EventArgs e)
                  // Put user code to initialize the page here
                  this.PageTitle = "Admin main menu";
                  HtmlGenericControl bodytag = (HtmlGenericControl)FindControl("body");
                  bodytag.Attributes["onload"] = "MM_showHideLayers('admin_show','','show')";

Here's the error message: Any ideas?

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:

Line 18:                   HtmlGenericControl bodytag = (HtmlGenericControl)FindControl("body");
Line 19:                   bodytag.Attributes["onload"] = "MM_showHideLayers('admin_show','','show')";
Line 20:             }
Line 21:
is bodytag null ?

can you also post your aspx ...
remember you need to put runat=server id= on the body tag.

w3digitalAuthor Commented:
Hi Grey

Yeah, I did ensure the runat=server etc but I was missing it - doh!

I have this:

<body id="body" runat="server">

then in the default.aspx.cs I have:

            private void Page_Load(object sender, System.EventArgs e)
                  HtmlGenericControl bodytag = (HtmlGenericControl)FindControl("body");
                  bodytag.Attributes["onload"] = "MM_showHideLayers('admin_show','','show')";

But I guess having the open body in the header.ascx file and the close body in the footer.ascx file is causing problems as I get the below error:

Parser Error Message: Unexpected end of file looking for </body> tag.

I imagine calling the code in the Page_Load event is the wrong place. Is there anywhere else I should put this code that will work? Or am I asking the impossible when <body> is in one user control and </body> is in another?

Thanks very much for your help you certainly deserve the points.
w3digitalAuthor Commented:
Ah, I see it's not the code, it's the actual Header.ascx user control that's playing up. I think I'm going to bring the body tag into the main file. That'll be simpler.

Yes, that sorts it!

Ta very much
no worries. glad to help ...

btw its a nice thing to put in a page base class for reuse :)
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.