Friday, 1 August 2014

Where to load data in the lifecycle of custom webpart

Usually in Page_Load or in CreateChildControls you should place the check for IsPostback and load the data only if the page is not in the postback mode. And also, you should load the data in all postback handlers.
This way, the data is loaded always and only once per page load.
But while this solution will work perfectly for a separated page, things get much more complicated if we are talking about webparts. The point is, that anything on the page could cause the postback, not only this particular webpart.
So, you probably will need to get the control which has caused the postback, and add additional check to ensure, that it is your control.
For instance, the code might look something like this:
public override void CreateChildControls()
{
    // ...
    var targetControlId = Page.Request.Params.Get("__EVENTTARGET");
    if (!Page.IsPostback || !myControlIds.Contains(targetControlId))
    {
        BindDataSource();
    }
    // ...
}
, there myControlIds contains collection of IDs of controls in your webpart, which can cause postback.

0 comments:

Post a Comment