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

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

    Instead of subclassing the RazorViewEngine, or replacing it outright, you can just alter existing RazorViewEngine's PartialViewLocationFormats property. This code goes in Application_Start:

    System.Web.Mvc.RazorViewEngine rve = (RazorViewEngine)ViewEngines.Engines
      .Where(e=>e.GetType()==typeof(RazorViewEngine))
      .FirstOrDefault();
    
    string[] additionalPartialViewLocations = new[] { 
      "~/Views/[YourCustomPathHere]"
    };
    
    if(rve!=null)
    {
      rve.PartialViewLocationFormats = rve.PartialViewLocationFormats
        .Union( additionalPartialViewLocations )
        .ToArray();
    }
    

提交回复
热议问题