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

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

    Most of the answers here, clear the existing locations by calling ViewEngines.Engines.Clear() and then add them back in again... there is no need to do this.

    We can simply add the new locations to the existing ones, as shown below:

    // note that the base class is RazorViewEngine, NOT WebFormViewEngine
    public class ExpandedViewEngine : RazorViewEngine
    {
        public ExpandedViewEngine()
        {
            var customViewSubfolders = new[] 
            {
                // {1} is conroller name, {0} is action name
                "~/Areas/AreaName/Views/Subfolder1/{1}/{0}.cshtml",
                "~/Areas/AreaName/Views/Subfolder1/Shared/{0}.cshtml"
            };
    
            var customPartialViewSubfolders = new[] 
            {
                "~/Areas/MyAreaName/Views/Subfolder1/{1}/Partials/{0}.cshtml",
                "~/Areas/MyAreaName/Views/Subfolder1/Shared/Partials/{0}.cshtml"
            };
    
            ViewLocationFormats = ViewLocationFormats.Union(customViewSubfolders).ToArray();
            PartialViewLocationFormats = PartialViewLocationFormats.Union(customPartialViewSubfolders).ToArray();
    
            // use the following if you want to extend the master locations
            // MasterLocationFormats = MasterLocationFormats.Union(new[] { "new master location" }).ToArray();   
        }
    }
    

    Now you can configure your project to use the above RazorViewEngine in Global.asax:

    protected void Application_Start()
    {
        ViewEngines.Engines.Add(new ExpandedViewEngine());
        // more configurations
    }
    

    See this tutoral for more info.

提交回复
热议问题