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

后端 未结 10 2318
故里飘歌
故里飘歌 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:16

    I did it this way in MVC 5. I didn't want to clear the default locations.

    Helper Class:

    namespace ConKit.Helpers
    {
        public static class AppStartHelper
        {
            public static void AddConKitViewLocations()
            {
                // get engine
                RazorViewEngine engine = ViewEngines.Engines.OfType().FirstOrDefault();
                if (engine == null)
                {
                    return;
                }
    
                // extend view locations
                engine.ViewLocationFormats =
                    engine.ViewLocationFormats.Concat(new string[] {
                        "~/Views/ConKit/{1}/{0}.cshtml",
                        "~/Views/ConKit/{0}.cshtml"
                    }).ToArray();
    
                // extend partial view locations
                engine.PartialViewLocationFormats =
                    engine.PartialViewLocationFormats.Concat(new string[] {
                        "~/Views/ConKit/{0}.cshtml"
                    }).ToArray();
            }
        }
    }
    

    And then in Application_Start:

    // Add ConKit View locations
    ConKit.Helpers.AppStartHelper.AddConKitViewLocations();
    

提交回复
热议问题