IsPostBack in ASP.NET

IsPostback is actually sending all the information from client to web server, then web server process all those contents and returns back to the client. Most of the time ASP.NET control will cause a post back (e. g. buttonclick) but some don't unless you tell them to do In certain events ( Listbox Index Changed,RadioButton Checked etc..) in an ASP.NET page upon which a PostBack might be needed.


If you want to follow along with me, copy and paste the following HTML in a web form.



       <table>
            <tr>
                <td></td>
                <td>Your Name</td>
                <td>
                    <asp:TextBox ID="TextBox1" runat="server" Width="167px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>Your Mail</td>
                <td>
                    <asp:TextBox ID="TextBox2" runat="server" Width="161px"></asp:TextBox>
                </td>
            </tr>
            <tr>
                <td>
        <asp:DropDownList ID="DropDownList1" runat="server" Height="17px" Width="182px">
        </asp:DropDownList>
                </td>
            </tr>
            <tr>
                <td>
                    <asp:Button ID="Button1" runat="server" Text="Submit" Width="103px"/>
                </td>
            </tr>

        </table>

Copy and Paste the below code.

protected void Page_Load(object sender, EventArgs e)
{
    LoadMonthDropDownList();
}

public void LoadMonthDropDownList()
{
       
ListItem  jan = new ListItem("January", "1");
        
ListItem  feb = new ListItem("February", "2");
        
ListItem  mar = new ListItem("March", "2");

        DropDownList1.Items.Add(jan);
        DropDownList1.Items.Add(feb);
        DropDownList1.Items.Add(mar);
}
protected void Button1_Click(object sender, EventArgs e)
{

} 

Now run the application. Look at the Month DropDownList. You will be look The Months are (January, February and March) are correctly shown. Now click the button once. Now Look DropDownlist the Month are duplicated


Cause for this duplication.
All ASP.NET server controls retain their state across postback. These controls  use of ViewState. So, when the first time loaded the result will be show correctly.

Now, when the client submit the button control, and the webform is posted back to the server for processing. During the Page initialization, ViewState restoration happens. During this stage, the city names are retrieved from the viewstate and added to the DropDownList. PageLoad event happens later in the life cycle of the webform. During page load we are again adding another set of Months. Hence, the duplication.

How to solve duplication
Use IsPostBack property. So, in the Page_Load, call LoadMonthDropDownList() method, if the request, is not a postback request. 

protected void Page_Load(object sender, EventArgs e)
{
    
if (!IsPostBack)
    {
        LoadMonthDropDownList();
    }
}



No comments:

Post a Comment