的IsPostBack在页面加载的实现 [英] Implementation of IsPostBack in page load

查看:139
本文介绍了的IsPostBack在页面加载的实现的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用ASP.NET,越多越如果(!的IsPostBack){} 看起来毫无意义......

The more I use ASP.NET, the more if (!IsPostBack) {} seems pointless...

第一个例子:

例如,我只是谷歌搜索的问题,他们说用这个作为解决方案的一部分:

For example, I just Googled an issue, they said use this as part of the solution:

if (!Page.IsPostBack)
{
   Page.LoadComplete += new EventHandler(Page_LoadComplete);
}

这不正是为codeD,LoadComplete只会在第一次加载火灾。点击一个按钮,或任何触发回传后,LoadComplete事件留给脱钩,从而跳过事件处理程序。因此,他们的修复只适用于第一次加载=一文不值。我及时注释掉如果(!Page.IsPostBack){} 现在事件始终触发应有的作用。

Which does exactly as coded, LoadComplete will only fire on the first load. After clicking a button, or anything that triggers a postback, the LoadComplete event is left unhooked, thus skipping the event handler. Therefore, their "fix" only works upon the first load = worthless. I promptly commented out the if (!Page.IsPostBack) {} and now the event always triggers as desired.

第二个例子:

我试图钩住事件动态创建的按钮(顺便说一句,我不能去上班[GRR!])。我看到的例子说明这一点:

I am attempting to hook events to a dynamically created button (which by the way, I can't get to work [GRR!]). I see examples showing this:

myEditToggleButton = new Button();
myEditToggleButton.ID = "editToggleButton"; 
//^GOTTA HAVE THIS FOR EVENTS TO WORK! (supposedly, I haven't seen it work...)
if (!IsPostBack)
{
   myEditToggleButton.Click += new EventHandler(myEditToggleButton_Click);
}
Controls.Add(myEditToggleButton);

像第一个例子,我的理解是,该事件不会在第一页加载后大呼过瘾,从而使按钮后点击惰性(因为单击触发回发)。

Like the first example, my understanding is that the event wouldn't be hooked after the first page load, thus the button is "inert" after one click (because clicking triggered a postback).

问:

当你应该使用如果(!的IsPostBack){} ?我猜测它与加价创建的控件只做

When should you use if (!IsPostBack) {}? I am guessing it has to do with mark-up created controls only.

推荐答案

在短,你用它每次你需要只执行第一次加载的东西。

In short, you use it everytime you need to execute something ONLY on first load.

Page.IsPostBack 的典型用法是数据绑定/控制初始化。

The classic usage of Page.IsPostBack is data binding / control initialization.

if(!Page.IsPostBack)
{
   //Control Initialization
   //Databinding
}

这是在的ViewState 了ControlState- 坚持的东西并不需要在每次回传,所以你检查要重建为,以避免执行不必要code这个条件。

Things that are persisted on ViewState and ControlState don't need to be recreated on every postback so you check for this condition in order to avoid executing unnecessary code.

另一个经典的使用越来越加工查询字符串参数。你不需要做回发。

Another classic usage is getting and processing Querystring parameters. You don't need to do that on postback.

这篇关于的IsPostBack在页面加载的实现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆