How can I create a variable with project-wide scope in ASP .NET?
I want to declare a variable in such a way that I can access that particular variable and its value in all the asp pages in th开发者_StackOverflowe project. Can anyone tell me how to declare a variable in C# such that it has project-wide scope?
You have a couple of choices and the best may require more specific information about what you are trying to accomplish. For example, do you need to be able to write to this variable as well?
But a simple approach is just to store it in the application object: Application["mydata"] = value;
Note that you can lose this data if your application is reset, which can happen from time to time. You can look at using cookies or a database to persist across resets.
Declare it as a "static" variable in a static class anywhere in the projects. You can declare it either as "internal" or "public".
However, you should always be careful about such a thing. If you need this, your design might need some work.
You can use a public property in the global.asax. That way you will be able to retrieve it from anywhere in the project.
global.asax:
private string _myvar = "";
public static string MyVar{ get { return _myvar; } set { _myvar = value; } }
any page code-behind:
string text = MyClassName.Global.MyVar
Based on what you said, I supose you want some kind of global variable. If tha's the case you should learn about the Application object and, probably, initialize your variable in the Application_Start method of global.asax file
If you need some generic approach. Create a project in your solution called Common as class library. Add a class file and add some public static members there . Compile it to dll, and you are now ready to use the members within the solution and if you wnt to use the same in some other application you can use too by adding reference.
But if you need it for some specific time you can use either of them stated above. In addition you can also use Session["MyObject"] = object_value. All have cons and pros. Google and use what ever suits you best. You have various options now, :)
Application scope defined within your global.ascx file.
Thus: Application["VariableName"] = value
.
If it is user and session specific, you could always store it in a session. It's simple as: Session["VarName"] = object;
You can use the HttpContext
to store items that need to be accessed throughout the lifecycle.
Example:
HttpContext.Items["myVariableKey"] = "my value";
The item put into that collection are only available for the current request.
精彩评论