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.