I want to declare a variable somewhere and initialize it in some action method. Then I want to use that assigned variable in other methods and in other's controller method.
How i can accomplish it?
I want to declare a variable somewhere and initialize it in some action method. Then I want to use that assigned variable in other methods and in other's controller method.
How i can accomplish it?
Have you tried putting these variables in a static class (as static variables)? Or just as a static variable in one of your classes. This way you can use the variables from everywhere in your application (if the assembly containing the class is referenced)
Declare the variable outside any methods(inside the class)
public partial class myClass
{
var _myVariable = "";
private void mymethod()
{
//your method code
}
}
_myVariable will be public to every method inside myClass
Well I can think of the following ways.
Static variable on a static class Be careful this mean this variable will be shared among the different users of your website.
Singleton class Some people like it and some hate it. Again this will be like static, the values will be shared between different visitors. Be careful also about threading here, and better to use some ready made tested implementations.
TempData or Session You can also store some value in temp data or session. Read about the lifetime of each and how to use. Check this [tutorial][2] or maybe [this][3]
Dependency Injection Here you can control the life time of the object. In Unity with MVC you can limit the object life time to be per request if you want a different value for each user. So you can create a class that has the variables you want, and register it, then use it in all places as you like. Check out this
You can implement it through a static class
just like in a traditional c# assembly
:
public static class Globals
{
public const Int32 BUFFER_SIZE = 10; // Unmodifiable
public static String FILE_NAME = "Output.txt"; // Modifiable
public static readonly String CODE_PREFIX = "US-"; // Unmodifiable
}
Please, refer to this old answer of mine for more information: