Click here to Skip to main content
15,886,199 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
Hello all,

We all know the problem of very huge view state when binding the dropdownlist for example. Few weeks ago I searched for it and the solution I found was to override OnInit method. Take this for example:
C#
protected override void OnInit(EventArgs e)
{
    ddlCustomers.DataSource = SystemData.GetAllCustomers();
    ddlCustomers.DataTextField = "CustomerName";
    ddlCustomers.DataBind();
    ddlCustomers.Items.Insert(0, new ListItem("Select Customers", "-1"));
    base.OnInit(e);
}

With this code the view state is only 3 to 4 lines (Well maybe because of a lot of controls I have :D )

Can some explain how this works ? I'm little bit familiar with ASP.net page life cycle but just can't figure out how this works.
Posted
Updated 17-Sep-14 3:41am
v2

1 solution

You'll get better results if you bind the list in the Init event of the control, rather than the page.
C#
protected void ddlCustomers_Init(object sender, EventArgs e)
{
    var ddl = (DropDownList)sender;
    ddl.DataSource = SystemData.GetAllCustomers();
    ddl.DataTextField = "CustomerName";
    ddl.DataBind();
    ddl.Items.Insert(0, new ListItem("Select Customers", "-1"));
}


The reason this works is that the control's Init event is fired before the control starts tracking changes to its ViewState. As a result, rather than storing the list of items in ViewState, the control simply assumes that the list will be recreated every time the page is loaded.

You want to do this in the control's Init event rather than the page's Init event, due to the way the event is raised:
C#
internal virtual void InitRecursive(Control namingContainer)
{
    // Pseudo-code:
    if (HasControls)
    {
        foreach (Control child in Controls)
        {
            child.UpdateNamingContainer(namingContainer);
            child.GenerateAutomaticID();
            child.Page = this.Page;

            child.InitRecursive(namingContainer);
        }

        Controls.SetCollectionReadOnly();
    }

    ApplySkin(Page);
    OnInit(EventArgs.Empty);
    TrackViewState();
}

The Init event is a bubbling event; it's raised on the child controls before it's raised on the parent. By the time the page's Init event is raised, the control is already tracking view-state.
 
Share this answer
 
Comments
Abdallah Al-Dalleh 19-Sep-14 14:22pm    
You have my respect sir! Perfect, helpful answer! :D

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900