代码之家  ›  专栏  ›  技术社区  ›  mare

ASP.NET MVC2中的自定义视图引擎不适用于区域

  •  1
  • mare  · 技术社区  · 14 年前

    到目前为止,我在asp.net mvc v1和v2中使用了下面的代码,但是当我今天向应用程序添加一个区域时,该区域的控制器在我的区域/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);
        }
    }
    
    3 回复  |  直到 14 年前
        1
  •  3
  •   MJBarlow    14 年前

    不是对您的问题的直接响应,而是其他读者可能会发现的有用信息,要使用自定义的viewengine,需要修改global.asax:

     void Application_Start(object sender, EventArgs e)
     {
      RegisterRoutes(RouteTable.Routes);
      ViewEngines.Engines.Clear();
      ViewEngines.Engines.Add(new PendingViewEngine());
     } 
    
    • 马特
        2
  •  2
  •   Ahmad    14 年前

    …搜索了这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. The Haack <-旧文章,但很好的介绍和概述
        3
  •  0
  •   Jab    14 年前

    创建区域时,它是否创建了AreaRegistration类?如果是的话,你的 global.asax.cs ?顾名思义,它向mvc注册区域。

        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
        }
    
    推荐文章