1

到目前为止,我在 ASP.NET MVC v1 和 v2 中使用了下面的代码,但是当我今天将一个区域添加到我的应用程序时,该区域的控制器在我的 Areas/Views/controllerView 文件夹中找不到任何视图。它发出了一个众所周知的异常,即它搜索了这 4 个标准文件夹,但没有在区域下查找。

如何更改代码以使其适用于区域?也许是 ASP.NET MVC 2 下支持区域的自定义视图引擎的示例?网络上关于它的信息非常稀少。。

这是代码:

public class PendingViewEngine : VirtualPathProviderViewEngine
{
    public PendingViewEngine()
    {
        // This is where we tell MVC where to look for our files. 
        /* {0} = view name or master page name       
         * {1} = controller name      */
        MasterLocationFormats = new[] {"~/Views/Shared/{0}.master", "~/Views/{0}.master"};
        ViewLocationFormats = new[]
                                {
                                    "~/Views/{1}/{0}.aspx", "~/Views/Shared/{0}.aspx", "~/Views/Shared/{0}.ascx",
                                    "~/Views/{1}/{0}.ascx"
                                };
        PartialViewLocationFormats = new[] {"~/Views/{1}/{0}.ascx", "~/Views/Shared/{0}.ascx"};
    }

    protected override IView CreatePartialView(ControllerContext controllerContext, string partialPath)
    {
        return new WebFormView(partialPath, "");
    }

    protected override IView CreateView(ControllerContext controllerContext, string viewPath, string masterPath)
    {
        return new WebFormView(viewPath, masterPath);
    }
}
4

3 回答 3

4

不是对您的问题的直接回应,而是其他读者可能会发现有用的东西,要使用自定义视图引擎,需要修改 global.asax:

 void Application_Start(object sender, EventArgs e)
 {
  RegisterRoutes(RouteTable.Routes);
  ViewEngines.Engines.Clear();
  ViewEngines.Engines.Add(new PendingViewEngine());
 } 
  • 马特
于 2010-10-04T12:42:45.993 回答
2

...搜索了这 4 个标准文件夹,但没有在“区域”下查看

这实际上是一个提示 - MVC 不知道在哪里以及如何查找区域视图,因为这些位置尚未在您的自定义视图引擎中定义。

您可能需要设置AreaPartialViewLocationFormats并在属性中包含Areas位置,ViewLocationFomats因为这是一个启用区域的应用程序。

ViewLocationFormats = new[]
{
   "~/Areas/Views/{1}/{0}.aspx",
   ...
};

并且可能...

AreaPartialViewLocationFormats = new[]
{
    "~/Areas/{1}/Views/{0}.ascx",
    "~/Areas/Views/{1}/{0}.ascx",
    "~/Views/Shared/{0}.ascx"
};

两个参考:

  1. MSDN <- 自 MVC1 以来可能已更新以包含新的区域内容,因此它为什么不工作
  2. Haack <- 旧帖子,但很好的介绍和概述
于 2010-05-07T07:07:16.820 回答
0

当您创建一个 Area 时,它是否创建了 AreaRegistration 类?如果是这样,你有这个global.asax.cs吗?顾名思义,它使用 MVC 注册区域。

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();
    }
于 2010-05-06T19:06:39.480 回答