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

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

    You can easily extend the WebFormViewEngine to specify all the locations you want to look in:

    public class CustomViewEngine : WebFormViewEngine
    {
        public CustomViewEngine()
        {
            var viewLocations =  new[] {  
                "~/Views/{1}/{0}.aspx",  
                "~/Views/{1}/{0}.ascx",  
                "~/Views/Shared/{0}.aspx",  
                "~/Views/Shared/{0}.ascx",  
                "~/AnotherPath/Views/{0}.ascx"
                // etc
            };
    
            this.PartialViewLocationFormats = viewLocations;
            this.ViewLocationFormats = viewLocations;
        }
    }
    

    Make sure you remember to register the view engine by modifying the Application_Start method in your Global.asax.cs

    protected void Application_Start()
    {
        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(new CustomViewEngine());
    }
    

提交回复
热议问题