【问题标题】:View error when invoking methods from base controller in MVC 5从 MVC 5 中的基本控制器调用方法时查看错误
【发布时间】:2017-03-18 23:41:13
【问题描述】:

我有以下控制器

public class StoreController : Controller
{
     public ActionResult Index()
     {
            var model = new SomeViewModel();
            return View(model);
     }
}

public class SofiaStoreController : StoreController
{
    public ActionResult GetIndex(string city)
    {
        return base.Index();
    }
}

当从派生类调用基索引方法时,我得到这个错误:

未找到视图“getindex”或其主视图或没有视图引擎 支持搜索的位置。以下位置是 搜索:

似乎 GetIndex() 方法默认在派生控制器的视图文件夹中查找视图,即使没有调用 View() 方法,但由于没有发生此类错误。

知道为什么该方法会隐式查找视图以及如何克服错误吗?

编辑:在花了一些时间研究这个问题后,我遇到了这两个帖子:http://howtoprogram.eu/question/asp-net-c-asp-net-mvc-inherited-controller-using-base-view,2445http://www.davidwhitney.co.uk/Blog/2010/01/19/asp-net-mvc-view-engine-that-supports-view-path-inheritance/ 似乎控制器继承并不是那么流行或直接的决定。我的问题的解决方案可能是: 1.不使用控制器继承 2.创建自定义视图引擎如第二个链接所示(高级) 3. 正如其他人在下面提到的 - 使用视图的完整路径或 RedirectToAction 也可以工作

【问题讨论】:

  • SofiaStoreController 继承自 StoreController 的原因是什么?
  • 我有一个带有抽象工厂方法的抽象 Store 类。然后 SofiaStore 和其他类继承它并覆盖工厂方法。与其依赖字符串来初始化存储类,不如拥有一个基本的 StoreController 并从它继承是一个更好的主意。每个派生的存储控制器初始化不同的存储类。
  • 一种选择是尝试重定向 stackoverflow.com/a/4909715/2048391

标签: c# asp.net-mvc inheritance


【解决方案1】:

它确实会根据您最初调用的 Action 方法名称来查找视图。如果您使用接受视图名称/路径的重载 View() 方法,则始终可以覆盖此行为:

public class StoreController : Controller
{
    public ActionResult Index(string viewName = "Index")
    {
        var model = new SomeViewModel();
        return View(viewName, model);
    }
}

public class SofiaStoreController : StoreController
{
    public ActionResult GetIndex(string city)
    {
        return base.Index();
    }
}

【讨论】:

  • 现在我有这个错误:没有找到视图“索引”或其主视图,或者没有视图引擎支持搜索的位置。搜索了以下位置: ~/Views/sofiastore/Index.cshtml ~/Views/sofiastore/Index.vbhtml ~/Views/Shared/Index.cshtml ~/Views/Shared/Index.vbhtml 。 GetIndex 方法继续在 Views/SofiaStore 文件夹中搜索视图,而我什么都没有。我的视图位于我已经拥有 Index.cshtml 的 Views/Store 文件夹中
  • 这只是一个如何覆盖应该使用哪个视图的示例。我不知道你的视图文件。您还可以传递路径而不仅仅是名称,例如。 "~/Views/existing-folder/exisitng-file.cshtml"
猜你喜欢
  • 1970-01-01
  • 2015-03-03
  • 2014-07-13
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-09-27
  • 2013-12-19
相关资源
最近更新 更多