简体   繁体   中英

which method in ASP.NET life-cycle is only called once? It is not fired during postback

Can we avoid using

If (!Postback) {.....code runs once....}

in Page_load()

I'm not particularly "hot" on ASP.NET events, but don't you think if there were a better approach (within the normal ASP.NET model) than the usual " if (!Postback) " one, everyone would already be using it?

I suspect there may be some cunning way of avoiding it, but only as "clever" code which will make it harder to maintain.

A single if statement isn't exactly horrendous...

(I'm not a big fan of the ASP.NET model to start with, admittedly... but if you're already within that model, there are worse things to contend with than this.)

This one is called only once:

 protected void Application_Start()

Google " global.asax " for more info.

If you want to happen the event not to occur in subsequest postbacks you have to write code in

if ( !IsPostBack )
{
} 

不,您不能,因为Web是无状态的,因此每个ASP.NET页在每次被请求时都需要加载。

There is no such event/method that you can hook up code in page life cycle that runs once. Every time the page instance passes through the same steps. That is the model.

There isn't an event that is only called once. In ASP.NET MVC you can distinguish between GET and POST using the AcceptVerbs attribute but that is just akin to IsPostBack , looking at the Request object.

Init is called before any ViewState is loaded so that might help, and the LoadViewState method is only called when a ViewState is loaded.

This is a simplification of the above link:

OnInit: 1
LoadViewState: 2
CreateChildControls: 3
OnLoad: 4
ShowButton: 5
OnPreRender: 6
Render: 7
OnUnload: 8

Number 3 can occur at any point in the chain.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM