Michael
Michael

Reputation: 155

BaseController ASPCore MVC

I want to implement a BaseController Action method that gets called either before or after the Action of the Controller class used to modify a View before its renders to Razor.

public class BaseViewModel
{
    public BaseViewModel() {}
    public string Property1 {get; set;}
}

public class ViewModel : BaseViewModel
{
    public ViewModel () : base() {}
    // Some View Methods
}

public class BaseController
{
    public BaseController();

    // here is where I want to put code to intercept the call to the 
    // AccountController when any action is performed and write to the
    // Property1  of the Base class of the ViewModel  class.
}


public class AccountController : BaseController
{
    public AccountController() : base() {}

    public IActionResult About()
    { 
       return(new ViewModel());
    }
}

I don't know how to do what I'm trying to explain, or if its even achievable. Could I get some feedback or recommendations?

The BaseViewModel will contains properties that are more generic to all pages like Culture, Title etc and not related to the ViewModel at all but perhaps renderded on the View.

Upvotes: 1

Views: 10085

Answers (1)

Matt
Matt

Reputation: 1374

You should be able to override OnActionExecuting:

// Custom Base controller.
public class BaseController : Controller
{
    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        // Do whatever here...
    }
}

// Account controller.
public class AccountController : BaseController
{
    // Action methods here...
}

Upvotes: 4

Related Questions