user1019830
user1019830

Reputation:

C# in Page_Load puts code on top of <html>

More specifically, I have made a small webpage using C# and a .aspx document. All C# code I have put in the <head> part of my document, inside Page_Load like this:

<script language="C#" runat="server">
protected void Page_Load(Object s, EventArgs e) {  
     Response.Write(@"<div class=""header"">Foo Bar</div>");
     ...
}
</script>

This works somehow, but the problem is that the html generated by this gets stuffed on top of the beginning <html> tag in the document which results in a broken character setting (doesn't read the meta tag?) and strange things not supposed to happen. I'm new to using ASP.NET and it's obvious. Where would I put all my statements so that they would be reachable from the <body> using <% delimiters?

Upvotes: 2

Views: 10255

Answers (1)

Joel Etherton
Joel Etherton

Reputation: 37533

You would put them in the body. This particular code doesn't do anything more than write directly to the spot where you've put it.

<body>

    <%= @"<div class=""header"">Foo Bar</div>"; %>

</body>

I'm sure this is just a test of something, but if you want to write to a specific place in the page you'd be better off using a label or literal control:

<head>
<script language="#C" runat="server">

    <script language="C#" runat="server">
    protected void Page_Load(Object s, EventArgs e)
    {  
         this.lblWriteToMe.Text = @"<div class=""header"">Foo Bar</div>");
         // ...
    }

    </script>
</head>

<body>
    <asp:Label ID="lblWriteToMe" runat="server" />
</body>
</html>

Edit: In order to place text in an html block you would put that directly into the html block you want it to appear in as I did in the first sample. It's a very "classic asp" method of doing it, though MVC is bringing the concept back. The script tag at the top can hold all of the method/event definitions and global variables/properties or whatever, but when you use Response.Write or <%= it will output it as soon as it appears. Keep in mind, that a standard webforms page has an event lifecycle that has to be considered and Response.Write can interfere with that. If you have output generated in methods or events, you would be better off posting that result into a control. This will allow the control to determine the proper order of rendering within the html block as it comes out in Page_Render.

Upvotes: 7

Related Questions