Tuesday, May 3, 2011

Masterpage Dropdown List not keeping Selected Index

Ok, my masterpage has a dropdown which controls size which affects a lot of things. I need to access the dropdown index from content pages so I do it using this code.

public partial class MasterPage : System.Web.UI.MasterPage
{
public DropDownList MySize { get { return _ddlSize; } }
}

I am using Ajax and when the size changes the menu on the Masterpage changes just fine.

But when I click on the updated menu it uses the zero index of the dropdown list on my contentpage even through visually it shows the size I selected.

  int size = Convert.ToInt32(Master.MySize.SelectedItem.Text); //Uses 0 index :(

I don't want to use Session, I just don't get why this doesn't work 100% of the time. Anyone have any ideas?

From stackoverflow
  • I figured it out!

    I set the dropdown to a public static object

    public static DropDownList MySize;
    

    Then I just set it equal to the page instance each time the masterpage loaded.

    protected void Page_Load(object sender, EventArgs e)
    {
        MySize = _ddlSize;
    }
    

    Calling the DropDownList is a little different since it's a static object.

    MasterPage.MySize.SelectedItem.Text
    

    But it works on all Content Pages that derive from the Masterpage.

    Jimmie R. Houts : Making it static only works if you want it to basically live forever, for all of your users. Static objects live in the iis worker process that your app is running in, which means that it is available globally, even across user sessions, until the worker process is killed or restarted (most of the time an app restart will get rid of it, but not always).
  • did you check this solution in a multi-user scenario, since the value is static it will be reflected across different users

    the view state set in the master page should retain the drop down lists value or try to use hidden controls to hold up the value

0 comments:

Post a Comment

Note: Only a member of this blog may post a comment.