Click here to Skip to main content
15,884,176 members
Articles / Web Development / ASP.NET
Tip/Trick

Order Your ASP.Net Embedded Code Blocks Correctly

Rate me:
Please Sign up or sign in to vote.
4.33/5 (2 votes)
4 Dec 2010CPOL 12.1K   3  
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:

HTML
<%@ 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:

HTML
<%@ 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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Web Developer
United States United States

  • Managing Your JavaScript Library in ASP.NET (if you work with ASP.net and you don't read that, you are dead to me).
  • Graduated summa cum laude with a BS in Computer Science.
  • Wrote some articles and some tips.
  • DDR ("New high score? What does that mean? Did I break it?"), ping pong, and volleyball enthusiast.
  • Software I have donated to (you should too):

Comments and Discussions

 
-- There are no messages in this forum --