Ajax – DropDownList in UpdatePanel

ajaxasp.netupdatepanel

In my project I have placed a dropdownlist in an updatepanel.what I wanted to do is to select a value from dropdownlist and use it in a session.

but whatever I do, it will always give me null value because of not checking "Enable AutoPostBack".and when I do this, it will refresh the page so this isn't what I wanted.

Best Answer

It sounds like you may not be using the UpdatePanel feature properly. If you have the UpdatePanel set to update when children fire events, only the UpdatePanel should refresh, not the entire page. The code below seems to behave similar to what you are seeking. When changing the drop down, only the update panel posts back to the server and when you refresh the page, you can get the value out of the session.

ASPX CODE

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <div>
        Current Time: <asp:Label ID="lblTime" runat="server" /><br />
        Session Value: <asp:Label ID="lblSessionValue" runat="server" /><br />
        <br />
        <asp:UpdatePanel ID="upSetSession" runat="server">
            <ContentTemplate>
                <asp:DropDownList ID="ddlMyList" runat="server" 
                    onselectedindexchanged="ddlMyList_SelectedIndexChanged"
                    AutoPostBack="true">
                    <asp:ListItem>Select One</asp:ListItem>
                    <asp:ListItem>Maybe</asp:ListItem>
                    <asp:ListItem>Yes</asp:ListItem>
                </asp:DropDownList>
            </ContentTemplate>
            <Triggers>
                <asp:AsyncPostBackTrigger ControlID="ddlMyList" 
                    EventName="SelectedIndexChanged" />
            </Triggers>
        </asp:UpdatePanel>
    </div>
</form>

CODE BEHIND

    protected void Page_Load(object sender, EventArgs e)
    {
        this.lblTime.Text = DateTime.Now.ToShortTimeString();
        if (Session["MyValue"] != null) 
            this.lblSessionValue.Text = Session["MyValue"].ToString();
    }

    protected void ddlMyList_SelectedIndexChanged(object sender, EventArgs e)
    {
        Session.Remove("MyValue");
        Session.Add("MyValue", this.ddlMyList.SelectedValue);
    }
Related Topic