I want to pass a string variable from a content page to a master page so that I can use it to change the Visible switch on and off in specific content tags.
I’ve accomplished it using a Session variable but I am wondering if there is a better way to pass the variable by making the variable set in the content page available to the master page?
(PS is anyone else having trouble with the search function returning a blank page?)
Honeymonster is [as usual] correct. Another option would be to use a set of interfaces to set up your “plumbing” to pass data between master pages and clients. Or from user controls to master pages. See this blog post for an example.
It’s not considered to be a good idea to directly change a variable that belongs to some other object, so instead usually use wrap a private variable with a public property - so you’ve better control over changes, coming from outside.
In C# 3.0 you can use Automatic Properties if you need a simple - and most often required - get/set accessor:
public string PageTypeVar { get; set; }
Or you can go the old way:
private string _pageTypeVar;
public string PageTypeVar
{
get { return _pageTypeVar; }
set { _pageTypeVar = value; }
}
One other thing to note–that private member will not persist it’s values across requests. If you want to keep the value, you need to “back” it with one of several options depending on how you want the storage to work. Options being:
Application: this variable is shared throughout the entire application. Effectively the same as declaring it “static”
Session: this means there is one shared value across a user’s session. If a user is using multiple browser windows, this could lead to race conditions.
ViewState: this lands the value in the page itself. Downside is it is serialized to the client on every request.
Context.Items: this does not live across requests, but it is handy for things like HTTP modules where you can “pass the buck” down the request pipeline.
In any case, wrapping the property in a real Property is the way to go as you can change the “backing” without effecting client code.