Question

Using Master Pages for Global Variables

Asked by: kashwmu

Hi All,
What i am trying to do is set a field that i have on the master page to hold a users login id so that it can be stored across multiple pages but this does not seem to work. I am far from and expert at ASP.NET but i am not changing the value just setting it and since i am using the same master page for all sub pages i believed this to work. What i am trying to accomplish is just a Global Variable like a windows form app. Session variables do not work because we are on a web farm and the computers are set not to use cookies and i really dont like to dirty the querystring everytime i go from page to page. Does anyone have a suggestion. Thanks

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-04-24 at 13:03:43ID24353812
Tags

ASP.NET

,

C#

,

Masterpages

Topics

Programming for ASP.NET

,

Visual Studio

,

Microsoft Visual C#.Net

Participating Experts
2
Points
500
Comments
16

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. asp.net cookies
    How can my asp.net web form find out weather the requesting browser has cookies enabled?
  2. QueryString Security in ASP.NET 2.0
    For security reasons, I'm trying to create an algorithm that prevents querystrings on a website from being hackable. To do this, I'm tacking a securely generated checksum based on the querystring value onto the end of the querystring as a page request begins using the Begin_...
  3. hide querystring in asp.net
    Is there a way in asp.net where we can avoid displaying the querystring in the browser window?? I know we can use sessions to avoid this problem.. but i am trying to access oracle reports engine (oracle reports 6i) and need to pass id as a parameter..like this.. www.someth...
  4. How to handle sessions in a web farm with no cookies??
    I'm trying to figure the best way to handle sessions in an e-Commerce web farm environment. What my setup is that I have a website that connects to a remote ODBC server to grab data for the website. The shopping cart generates server side session files, no client cookies at a...
  5. Asp.net in web farm environment
    We have a web farm setup using 3 windows 2003 servers with IIS 6.0. The actual web files are stored on a shared directory located on a fourth server. We moved an asp.net app called Xigla Absolute Video Channel (www.xigla.com) from a single server running Windows 2003 and II...

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: davrob60Posted on 2009-04-24 at 13:10:28ID: 24228756

i would not use  Master Pages for Global Variables.

but do you know you could store session state on  SQL server???

http://support.microsoft.com/kb/317604

 

by: abelPosted on 2009-04-24 at 13:11:34ID: 24228770

A global variable is not a good idea for this, because that will be really global (i.e., visible to every page on any request) and one variable can only hold one value.

The thing you are looking for is Sessin. If you are on C# and I think you are, you can set the session like this:

Session["userid"] = myUserId;

and you can retrieve it like this:

int earlierStoredUserId = 0;
int.TryParse(Session["userid"], out earlierStoredUserId);

which will store it in the variable earlierStoredUserId, which will contain zero if there wasn't a userid to begin with (i.e. on the first visit of a new user to your page).

This session is available to every page and every masterpage and every control. It is meant for this kind of storage and will be unique per user, but can be retrieved at any time.

 

by: abelPosted on 2009-04-24 at 13:12:49ID: 24228788

oops, I didn't see that last sentence... you don't want to use sessions... But if you are on a web farm, I'm sure you use a state server or, like davrob60 suggests, sql server for it. Both are quite easy to setup.

 

by: davrob60Posted on 2009-04-24 at 13:19:41ID: 24228859

If you really what to use store a global variable on the masterpage, you could use a hiddencontrol to store the values. persistence of the values will be assumed by the ViewState mecanism.

 

by: abelPosted on 2009-04-24 at 14:06:33ID: 24229230

Agreed, and you can use a public readonly property on the masterpage

public int UserId
{
   get
    {
        return int.Parse(myHiddenField.Value);
   }
}

and on the page you can do the followoing:

<%@ MasterType VirtualPath="~/masterpage.master" %>

in your page ASPX and then in your code behind file, you can use the following to access your masterpage data:

int myUserIdVariableOnThePage = Master.UserId;

which will effectively be the way I would go about implementing the proposal of davrob60 in the last post, which fits your original request to use the masterpage for storing data (ViewState).

-- Abel --

 

by: kashwmuPosted on 2009-04-27 at 12:32:56ID: 24244913

Ok, you guys are going in the right direction and i appreciate that i just need a little more help it looks like.
I added the <%@ MasterType VirtualPath="~/masterpage.master" %> directive to the page that i am trying to pull the data from and i was not able to see the public string that i declared. There was no Master just the normal MasterPage that is standard. What i was tryign to do before was i created two labels on the master page and then i was loading them with data during my initial load of the program using a FindControl(). Then i could set it to a value but that value would never persist accross multiple pages. This was a mystery to me thus the reason i asked the question. I have no problem with the public property idea i just did what you posted and was not able to see the property. Any help is appreciated. Thanks

 

by: davrob60Posted on 2009-04-27 at 12:50:21ID: 24245066

"but that value would never persist across multiple pages."

That what I was worrying about. I searshed for any reference about viewstate and masterpage and I found nothing revalant, (at first). but i just fond something.

the problem is that ViewState is being saved/restored across same page round trips. The problem is that a master page is not a page itself and that why never persist across multiple pages.

http://forums.asp.net/p/1257612/2341989.aspx#2341989

http://forums.asp.net/p/1127427/1784044.aspx#1784044

so I think you must rely on the session option.

 

by: kashwmuPosted on 2009-04-27 at 13:24:42ID: 24245337

Using a session might be the correct option and i will have to get the people to set that up but i was wondering if anyone has any info on the master page using a public property. I have found many pages that say all you have to do is add the <%MasterType%> directive and they you can access this by just using this.Master but that is not true for me. Can anyone help with that like was stated by ABEL in an earlier comment. Thanks

 

by: davrob60Posted on 2009-04-27 at 13:39:27ID: 24245466

The "MasterType" thing is just something to "interface" with the masterpage. It used, if you have something you need to access form the content page.

It could be use, as an example, to update a title or read the content of a textbox, but i dont think it could be applied to your case.

 

by: abelPosted on 2009-04-27 at 14:30:52ID: 24245867

Apparently there are some questions about my approach. Just to be sure that we're on the same page, I tested my approach step by step. Here's what I did:

  1. Add a master page to my existing project with the name MyMaster.master 
  2. Add the following to the master page code-behind (see code section)
     
  3. Add a page to my project called mypage.aspx 
  4. Add the following to that page: <%@ MasterType VirtualPath="~/MyMaster.Master" %> 
  5. Went to the code behind of the mypage.aspx page and type "Master.Us" inside a method. The result is in the screenshot: 
If you do that too, what error do you get or, more precisely, what happens?

If you have this example working, you can make use of the viewstate through a backdoor by using a hidden field with a runat=server, you can even set its Visible=False to prevent it being rendered into the HTML and you can use its value the way you would use any value that you want to persist with a page.

-- Abel --

namespace WebApplication1
{
    public partial class MyMaster : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
 
        }
 
        public int UserTest = 30;
        public int UserId
        {
            get
            {
                return 20;
            }
        }
    }
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:

Select allOpen in new window

  • ScreenShot243.png
    • 17 KB

    The available properties from my own special MyMaster.master: UserId (property) and UserTest (field)

    The available properties from my own special MyMaster.master: UserId (property) and UserTest (field)
 

by: kashwmuPosted on 2009-04-28 at 09:40:42ID: 24252542

Your example seems easy to me i just can't get it to work. When i type Master.* it does not bring up the property that i am trying to use. I am really not sure what i am doing different from you.

1. I have 2 pages, MasterPage.Master and Report.aspx
2. I added <%@ MasterType VirtualPath="~/MasterPage.master" %> to Report.aspx.
3. The below code is the MasterPage.Master code.
4. The screen shot is what i see when i type Master.Lo into the code. I do not see the property that i am trying to find.

Sorry about all of this hassle i just don't understand why it does not work.

Thanks for all of the assistance.

//Master Page Code
public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {
        
    }
 
    public int LoginID
    {
        get { return 20; }
    } 
 
}
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:

Select allOpen in new window

 

by: davrob60Posted on 2009-04-28 at 09:57:06ID: 24252675

hum....

The plan was to use the ViewState to "hold" the value across pages using a control on a master page. The problem, has i discovered after my second post, is that I got information that a master page is not a page itself. So, if it`s true, ViewState cannot be used so share a value across pages.

You could continue on that trail, but, if you make that masterpage property work, I doubt the it will be useful because it will be reinitialized between each pages..

 

by: abelPosted on 2009-04-28 at 10:47:51ID: 24253189

> 2. I added <%@ MasterType VirtualPath="~/MasterPage.master" %> to Report.aspx.

does your path resolve? I.e., is the master in the root dir? Is your MasterPageFile set for that page?

What is the version of your .NET? Might it be that on .NET 2.0 (if you have that) it doesn't work? I have 3.5, though I do remember that I used this technique before I moved over.

As you notice, I'm a bit running out of ideas. But, as davrob60 excellently points out: the viewstate is a per-page state, not a per-session state, and if you use the viewstate from the master, that's fine, but it will be unavailable across pages. I just tested it to be sure, and it is correct, unfortunately.

Still, using a masterpage to hold a property that accesses a generic value that you keep inside a session is very good practice, because you make it accessible for anybody using that masterpage.

-- Abel --

 

by: kashwmuPosted on 2009-04-28 at 13:54:16ID: 24255035

It could be a .NET 3.5 thing but as i read around it looks like it can be acomplished on 2.0 but i believe that we all have spent enough time on it and since i can not get it to work i am going to just use a state server for sessions. I appreciate all of the help and since i am new at this i will try and give you both some points. I appoligise if i screw something up.

 

by: kashwmuPosted on 2009-04-28 at 13:56:08ID: 31574391

My problem was solved but the final few messages did not get resloved for me.

 

by: abelPosted on 2009-04-28 at 16:26:12ID: 24256144

> I appoligise if i screw something up.

no, you didn't screw anything up. welcome to EE! ;-)

> My problem was solved but the final few messages did not get resloved for me.

I would, however, be intrigued to here of a solution if you find out what's up, because this is one of the more common scenario's with .NET and I feel like overlooking something. So, you're on .NET 2.0, but you're right, it can be done. This story tells what's going on behind the scenes, maybe you want to check if those methods are actually created for you: http://odetocode.com/Blogs/scott/archive/2005/07/16/1944.aspx (and if not, check whether you have the latest bug-fixes downloaded from Microsoft and/or use the CType/DirectCast workaround that is laid out on that very same page)

-- Abel --

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...