When are ASP.NET code blocks, e.g., <%= %> executed in the page lifecycle?

穿精又带淫゛_ 提交于 2019-12-10 15:20:02

问题


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?


回答1:


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



来源:https://stackoverflow.com/questions/7251330/when-are-asp-net-code-blocks-e-g-executed-in-the-page-lifecycle

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!