When I am databinding an entire page, I will do something like this:
Blah blah…
<%# SomeProperty == "GoodBye" ? "See you later" : "Hello" %>
And that works beatifully. However, often I will not use databinding for an entire page and write things the “clasic” ASP.NET way. E.g., in the code behind I will have something like:
lblSomeMessage.Text = SomeProperty == "GoodBye" ? "See you later" : "Hello";
And then .aspx would have
<asp:label runat="server" id="lblSomeMessage"/>
But what I want to do both…sort of. What I would like to do is not use databinding syntax but instead a code block:
<%= SomeProperty == "GoodBye" ? "See you later" : "Hello" %>
^^^^
Noe the output tag syntax. Now, the question is, when will this tag actually be evaluated? Suppose I don’t set the SomeProperty property until the OnPreRender event. Is that too late? In my testing I actually did this:
<%= SomeProperty == "GoodBye" ? + new System.Diagnostics.StackTrace().ToString() : "OH NO!" %>
And according to the stacktrace:
ASP.webform1_aspx.__Renderform1(HtmlTextWriter __w, Control
parameterContainer) at
System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer,
ICollection children) at
System.Web.UI.HtmlControls.HtmlForm.RenderChildren(HtmlTextWriter
writer)…
It happens during render, which is perfect. But is this guaranteed? Any gotchas to this rule?
Yes, it’s guaranteed to be
Render.“An embedded code block is server code that executes during the page’s render phase.” – http://msdn.microsoft.com/en-us/library/ms178135.aspx