4

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?

aquinas
  • 23,318
  • 5
  • 58
  • 81
  • 2
    fyi: use `<%:` instead of `<%=` whenever you can. It automatically html-encodes the output, and you can even change the encoding engine if you want. – Joel Coehoorn Aug 31 '11 at 02:37
  • Agreed. In this particular case I am outputting a static string, but point well taken. – aquinas Aug 31 '11 at 02:50

1 Answers1

5

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

nw.
  • 4,795
  • 8
  • 37
  • 42