views:

1153

answers:

2

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?

A: 

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.

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).
Jimmie R. Houts
I have tested this method over multiple users and it works fine. It does bring up a good question in how can I make globally static variables that live over multiple sessions, because this isn't the way to do it.
A: 

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

Rony
You bring up a very good point. I have closed the browser and reopened it and the values aren't retained. I think it works, but now I am a little paranoid. Thanks for pointing that out.