简体   繁体   中英

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.

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);
}

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM