Click here to Skip to main content
Click here to Skip to main content

Tagged as

Go to top

Order Your ASP.Net Embedded Code Blocks Correctly

, 4 Dec 2010
Rate this:
Please Sign up or sign in to vote.
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.

License

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

Share

About the Author

AspDotNetDev
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 --
| Advertise | Privacy | Mobile
Web04 | 2.8.140926.1 | Last Updated 4 Dec 2010
Article Copyright 2010 by AspDotNetDev
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid