Wednesday, July 23, 2008

The Importance of Page.IsPostBack

For most of the time, we should think about adding if(!Page.IsPostBack) block in Page_Load event of our webpage. Since ViewState of all the webcontrols are enabled by default, most of the time the logic in Page_Load event is supposed to be executed only during the first time webpage is loaded. If we forget to wrap the logic inside the if block when we are supposed to do so, not only can it causes inefficiency, but leads to bugs.

Here is an example. (Refer to ASP.NET security tutorial #10 http://www.asp.net/learn/security/tutorial-10-cs.aspx, step 4)

If we don't wrap the following logic inside if(!Page.IsPostBack) block:

// Reference the SpecifyRolesStep WizardStep
WizardStep SpecifyRolesStep = RegisterUserWithRoles.FindControl("SpecifyRolesStep") as WizardStep;
// Reference the RoleList CheckBoxList
CheckBoxList RoleList = SpecifyRolesStep.FindControl("RoleList") as CheckBoxList;
// Bind the set of roles to RoleList
RoleList.DataSource = Roles.GetAllRoles();
RoleList.DataBind();

something unexpected will happen.

During the second step of the wizard, if we check any role we'd like to assign to the newly created user, it will fail to assign. After we check any CheckBox on the CheckBoxList and press the next button, the logic in Page_Load event is executed again. This will cause the RoleList to be bound again. It seems to be harmless at first, but the truth is, RoleList.DataBind() will clear any change made to the CheckBoxList. Hence, even if we've checked some CheckBox in the RoleList the second step, they all become unchecked now.

So, in this case, there is no reason not to use if(!Page.IsPostBack) block.

Perhaps saying "most of the time if(!Page.IsPostBack) block should be added in Page_Load event" is a bit absolute; but for me, I'll wrap the logic in the block every time; unless there is a reason convinces me not to do so.

No comments: