65.9K
CodeProject is changing. Read more.
Home

Order Your ASP.Net Embedded Code Blocks Correctly

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.33/5 (2 votes)

Dec 3, 2010

CPOL
viewsIcon

12321

If you place your ASP.Net embedded code blocks after the controls they reference, you may not get the output you expected.

As explained here, the code in embedded code blocks gets run as part of the rendering portion of the ASP.NET page life cycle. This caused me some trouble when I tried to set the value of a Literal control after that control had been rendered:
<%@ Page Language="vb" %>
<html>
    <head>
        <title>Literal First Does Not Work</title>
    </head>
    <body>
        <form runat="server">
            <asp:Literal runat="server" ID="litHello" />
            <%
                litHello.Text = "Hello World"
            %>
        </form>
    </body>
</html>
You don't get an exception to help you out either... the content simply does not render. The reason for this is that the Literal control appears before the embedded code block, which means it gets rendered (i.e., converted to HTML) before the code block is run. So, the code block does set the Text property of the control, but since the control has already been rendered, that Text property is ignored. Here is the correct way to go about doing this:
<%@ Page Language="vb" %>
<html>
    <head>
        <title>Literal Last Does Work</title>
    </head>
    <body>
        <form runat="server">
            <%
                litHello.Text = "Hello World"
            %>
            <asp:Literal runat="server" ID="litHello" />
        </form>
    </body>
</html>
The code block gets run first, so it sets the Text property before it is used to render the Literal control.