How can I make a constructor in my controller?

0

Can I make a constructor of my controller to instantiate the instances that I must consume from the models or methods of my application ?. How would it be?

Example:

My controller

public class MiControlController : Controller
{
    private MiModelo _MiModelo;

    public MiControl()
    {
        _MiModelo = new MiModelo();
    }

    // Logic
}
    
asked by vcasas 06.06.2018 в 16:16
source

2 answers

0

Finally solve it in the following way. (I'd like you to check it to see if it's really all right).

public class ProfileController : Controller
{
    private MiClase _MiClase;

    public ProfileController()
    {
        _MiClase = new MiClase();
    }

    public ActionResult Index()
    {
        ViewBag.Dato1 = _MiClase.MiMetodoGetDato1();

        return View();
    }
}
    
answered by 06.06.2018 / 16:37
source
0

There are several ways to do what I imagine you want to do, which is to instantiate an object and consume its methods.

Option 1: using the driver's constructor

public class MyOwnController : Controller
{
    private MyClass model;
    public MyOwnController()
    {
        model = new MyClass();
    }

    public ActionResult Index()
    {
        return View(model.GetInfo());
    }
}

Option 2: as property

public class MyOwnController : Controller
{
    private MyClass model = new MyClass();

    public ActionResult Index()
    {
        return View(model.GetInfo());
    }
}

or

public class MyOwnController : Controller
{
    private MyClass model { get { return new MyClass(); } }

    public ActionResult Index()
    {
        return View(model.GetInfo());
    }
}

Option 3: class methods

If you are going to execute a method that will return information based on the context, you can choose to leave the method as static and delegate the task:

public class MyClass
{
    public static string GetInfo(string dato1, int dato2...)
    {
        return ...
    }
}

public class MyOwnController : Controller
{
    public ActionResult UnaVista(string dato1, int dato2)
    {
        return View(MyClass.GetInfo(dato1, dato2));
    }
}

In fact there are more ways, personally I would recommend using option 3 since it is more focused on the concept of MVC itself.

    
answered by 07.06.2018 в 18:42