Can I specify a custom location to “search for views” in ASP.NET MVC?

后端 未结 10 2322
故里飘歌
故里飘歌 2020-11-22 06:08

I have the following layout for my mvc project:

  • /Controllers
    • /Demo
    • /Demo/DemoArea1Controller
    • /Demo/DemoArea2Controller
    • etc
10条回答
  •  执笔经年
    2020-11-22 06:40

    There's actually a lot easier method than hardcoding the paths into your constructor. Below is an example of extending the Razor engine to add new paths. One thing I'm not entirely sure about is whether the paths you add here will be cached:

    public class ExtendedRazorViewEngine : RazorViewEngine
    {
        public void AddViewLocationFormat(string paths)
        {
            List existingPaths = new List(ViewLocationFormats);
            existingPaths.Add(paths);
    
            ViewLocationFormats = existingPaths.ToArray();
        }
    
        public void AddPartialViewLocationFormat(string paths)
        {
            List existingPaths = new List(PartialViewLocationFormats);
            existingPaths.Add(paths);
    
            PartialViewLocationFormats = existingPaths.ToArray();
        }
    }
    

    And your Global.asax.cs

    protected void Application_Start()
    {
        ViewEngines.Engines.Clear();
    
        ExtendedRazorViewEngine engine = new ExtendedRazorViewEngine();
        engine.AddViewLocationFormat("~/MyThemes/{1}/{0}.cshtml");
        engine.AddViewLocationFormat("~/MyThemes/{1}/{0}.vbhtml");
    
        // Add a shared location too, as the lines above are controller specific
        engine.AddPartialViewLocationFormat("~/MyThemes/{0}.cshtml");
        engine.AddPartialViewLocationFormat("~/MyThemes/{0}.vbhtml");
    
        ViewEngines.Engines.Add(engine);
    
        AreaRegistration.RegisterAllAreas();
        RegisterRoutes(RouteTable.Routes);
    }
    

    One thing to note: your custom location will need the ViewStart.cshtml file in its root.

提交回复
热议问题