简体   繁体   中英

How can i declare a variable globally so that i can access it across all other viwes in mvc

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:

  1. If the class is in a namespace not known to the views you can fully-qualify the class name, or add a @using directive or modify the application's config to auto-import that namespace into views.
  2. If the value has any association with an existing model, it probably belongs on that model. A 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.
  3. A 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM