Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC Global Variables

How do you declare global variables in ASP.NET MVC?

like image 472
Beginner Avatar asked Feb 25 '11 14:02

Beginner


People also ask

How can use global variable in ASP NET MVC?

You can put them in the Application: Application["GlobalVar"] = 1234; They are only global within the current IIS / Virtual applicition. This means, on a webfarm they are local to the server, and within the virtual directory that is the root of the application.

How do you set a global variable in .NET core?

To get started in adding your static global variables in ASP.NET, create the App_Code folder. Then Right-click on your project name and select "Add ASP.NET Folder" and then App_Code. Here is the code you can put in the class file. Static The Global class is static.

How do I create a global variable in razor view?

To declare a variable in the View using Razor syntax, we need to first create a code block by using @{ and } and then we can use the same syntax we use in the C#. In the above code, notice that we have created the Code block and then start writing C# syntax to declare and assign the variables.

Should you use global variables in C#?

Does C# support Global Variables? C# is an object-oriented programming (OOP) language and does not support global variables directly. The solution is to add a static class containing the global variables. Using a global variable violates the OOP concept a bit, but can be very useful in certain circumstances.


3 Answers

Technically any static variable or Property on a class, anywhere in your project, will be a Global variable e.g.

public static class MyGlobalVariables
{
    public static string MyGlobalString { get; set; }
}

But as @SLaks says, they can 'potentially' be bad practice and dangerous, if not handled correctly. For instance, in that above example, you would have multiple requests (threads) trying to access the same Property, which could be an issue if it was a complex type or a collection, you would have to implement some form of locking.

like image 165
Sunday Ironfoot Avatar answered Oct 17 '22 21:10

Sunday Ironfoot


public static class GlobalVariables
{
    // readonly variable
    public static string Foo
    {
        get
        {
            return "foo";
        }
    }

    // read-write variable
    public static string Bar
    {
        get
        {
            return HttpContext.Current.Application["Bar"] as string;
        }
        set
        {
            HttpContext.Current.Application["Bar"] = value;
        }
    }
}
like image 51
abatishchev Avatar answered Oct 17 '22 22:10

abatishchev


You can put them in the Application:

Application["GlobalVar"] = 1234;

They are only global within the current IIS / Virtual applicition. This means, on a webfarm they are local to the server, and within the virtual directory that is the root of the application.

like image 24
GvS Avatar answered Oct 17 '22 21:10

GvS