开发者

Why can ASP.net code in VBScript tags run at page load despite being in no sub or method?

I don开发者_JAVA百科't use Visual Studio to write ASP.net websites.

If I put ASP.net code in VBScript tags <% at the top of my .aspx document, it runs without needing to be in a sub page_load.

In fact, I am including another .aspx file that does contain a page_load sub that runs on every page of this small project.

Why don't I get errors like

Statement cannot appear outside of a method body

with this implementation?


These tags, called Code Render Blocks, are there by design and covered in the documentation here: http://msdn.microsoft.com/en-us/library/k6xeyd4z(v=VS.71).aspx

I have yet to find a reason that Microsoft included them, other than that it's an easy way to put server-side variables or method output into the page. I believe that it's a holdover from classic ASP.

Based on the behavior, the reason they don't throw an error is because they are evaluated during the Page_Render phase (putting the ececution within a method body). You can see this by stepping through your code in Visual Studio.

Personally, however, I prefer to use Labels or other controls, and set the text in the code-behind. There are a few exceptions where I've used this syntax for one reason, and one reason only: So that I could change the code without having to recompile the web app.


I think this is allowed for data binding and for compatibility with classic asp.


They are called Embedded Code Blocks and they are executed during Page's Render event according to this post.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜