I need to declare variable globally so that i can use it across all applications. Basically i want to declare a stack globally so that i can use it across all views in my MVC application.
Generally there aren't "global variables" in C#. However, you can create a static
member of a class and access it essentially "globally". For example, suppose you create this in your models:
public class GlobalValues
{
public static string MyValue { get; set; } = "This is globally accessible.";
}
Then anywhere in your application you can reference it with:
GlobalValues.MyValue
So in your view you might simply have:
@GlobalValues.MyValue
A few things to note would be:
@using
directive or modify the application's config to auto-import that namespace into views.GlobalValues
class here was just for demonstration. Having a dumping ground of things you don't know where else to put can become a maintenance nightmare quickly in a codebase.string
is of course just an example here. Your property can be any type you like. If it's fairly complex and needs more initialization logic, a static constructor would be where you put that logic.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.