I am new to ASP .NET, I am trying to setup a website in Visual Studio with C#.
My background is in PHP. In that language, if I want a variable to be accessible by every page, simply put it in a include file.
Is there anything similar to C# and ASP .NET? There is an site.master page, but I am not sure how to access it’s variables from page contents. Thanks in advance.
You have a few different options here:
Session Variables
Session variables are stored in the server’s memory for each user, and can be read and written to as often as required. These are limited to a per-user basis, so if you want to hold a single variable for all users, then this isn’t the way to go.
Usage:
You can to set a user’s session variable in your global.asax file under the session_start event handler if required.
Application/Cache Variables
Application and Cache variables are accessible by any user, and can be get/set as required. The only difference between the two is that Cache variables can expire, which makes them useful for things such as database query results, which can be held for a while before they’re out of date.
Usage:
You can set an application variable in your global.asax file in the application_start event handler if required.
Web.Config
This is probably the preferred way of storing constants in your application, since they are stored as “Application Settings” and changed in your web.config file as required without having to recompile your site. application settings are stored in the
<appsettings>area of your file using this syntax:Web.config values should be considered read-only in your code, and can simply be accessed using this code in your pages:
Static Variables
Alternatively, you could just create a class that contains a static property to hold your variable like this:
And then access it like this:
I actually use a combination of the latter two solutions in my code. I’ll keep my settings in my web.config file, and then create a class called
ApplicationSettingsthat reads the values from web.config when required using static properties.Hope this helps