Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chaos when incorrectly writing to writer during Render() method

Could someone please explain what is going on here.

I have the following markup:

<html>
<head runat="server">
    <title>My title</title>
    <my:MyControl runat="server" ID="myControl" />
</head>
...

My custom control is something like this:

public MyControl : Control
{
    protected override void Render(HtmlTextWriter writer)
    {
        writer.Write("<script>this is my script</script>");
        base.Render(writer);
    }
}

When the page is rendered, the entire top half of the head is chopped off, so the html renders like this:

<html>
    <script>this is my script</script>
</head>

The solution is to call writer.Write after base.Render, like this:

base.Render(writer);
writer.Write("<script>this is my script</script>");

Why?!

UPDATE

I'm surprised at the amount of interest in this question!

I found out why the top portion of my head tag was being removed - it was a bug with an HttpHandler that I use to 'clean' html (it moves scripts to the bottom etc).

This still doesn't explain exactly why changing the order of the render method would cause the bug to disappear, but I'm sure there is a logical explanation for it all!

like image 534
cbp Avatar asked Jun 07 '11 07:06

cbp


1 Answers

You simply are overwriting your body content with what are you returning from your function:

<script>this is my script</script>
like image 74
Adrian Avatar answered Nov 06 '22 00:11

Adrian