-1

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?

6
  • What programming language are you talking about ?
    – Avinash
    Dec 12, 2017 at 5:34
  • MVC (Model View Controller)
    – subham
    Dec 12, 2017 at 5:36
  • MVC is an architectural pattern not a programming language
    – Avinash
    Dec 12, 2017 at 5:38
  • I use java to build MVC app and my friend uses python to build MVC app :)
    – Avinash
    Dec 12, 2017 at 6:17

4 Answers 4

0

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:

https://stackoverflow.com/a/14368428/796085

0

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)

0

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

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.