ASpencer
ASpencer

Reputation: 1363

ASP.NET MVC Inherited Controller using base view

I've run into a bit of an odd problem, and I'm not 100% sure what's the way to resolve this.

Given an MVC controller, BaseController (Minimal example below)

BaseController : Controller 
{
    public ActionResult LotsOfActions() 
    {
        //this calls a view that renderActions AnAction(SomeModel) a bunch of times.
    }

    public ActionResult AnAction(Object SomeModel) 
    { 
        //do stuff
        return View("AnAction",TemplateFromCode,ViewModel); //Depending on something in SomeModel, we want a different template for this.
    }
}

DerivedController : BaseController 
{
    public override ActionResult LotsOfActions() 
    {
        //this calls a view that renderActions BaseController.AnAction(SomeModel) a bunch of times but with different logic.
    }
}

When AnAction is called on DerivedController, it's attempting to use DerivedController/AnAction.cshtml (or whatever name), which I don't need to exist because the subview should be the same, and so I get a view not found error. How do I get this to use BaseController/AnAction.cshtml as I intend it to? I don't want to use the shared view folder for this, because that's scanned before DerivedController in case I do want to override this view for something else that is a subclass of BaseController.

Upvotes: 2

Views: 1969

Answers (2)

DavidG
DavidG

Reputation: 118977

The easiest way is just to be explicit in your base class by specifying the full path to the view, like this:

public ActionResult AnAction(Object SomeModel) 
{ 
    //do stuff
    return View("~/Views/Base/AnAction.cshtml",TemplateFromCode,ViewModel);
}

Upvotes: 2

Paul Swetz
Paul Swetz

Reputation: 2254

Instead of inheriting the base controller why not have anything calling AnAction just call that controller? Usually controller inheritance is used for internal details and not public action method overrides.

Otherwise you are stuck with what DavidG suggested since the view path is auto-constructed from the realized controllers location, not the base controllers.

Upvotes: 1

Related Questions