简体   繁体   English

使用基本视图的ASP.NET MVC继承的控制器

[英]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. 我遇到了一个奇怪的问题,但我不确定100%解决此问题的方法。

Given an MVC controller, BaseController (Minimal example below) 给定一个MVC控制器BaseController(下面的最小示例)

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. 当在DerivedController上调用AnAction时,它尝试使用DerivedController / AnAction.cshtml(或任何名称),由于子视图应该相同,所以我不需要存在该名称,因此出现视图未找到错误。 How do I get this to use BaseController/AnAction.cshtml as I intend it to? 我如何按预期使用BaseController / AnAction.cshtml? 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. 我不想为此使用共享视图文件夹,因为在DerivedController之前会先扫描该文件夹,以防万一我想为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? 与其继承基控制器,为什么不调用AnAction只是调用该控制器呢? 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. 否则,您会受制于DavidG的建议,因为视图路径是从已实现的控制器位置(而不是基本控制器)自动构建的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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