Search code examples
c#asp.net-mvcrazorviewengine

how to change order of search viewLocation in asp.net mvc?


In my project, I have a folder called Common, and I want to Asp.net Mvc search the Common folder for finding Views, instead of share folder.

In other words, the order of search location view is as follows:

~/Views/Home/Index.cshtml
~/Views/Home/Index.vbhtml
~/Views/Common/Index.cshtml
~/Views/Common/Index.vbhtml

Solution

  • you can create custom class inherits RazorViewEngine

    usin System.Web.Mvc
    namespace Views.Infrastructure{
    public class CustomrazorViewEngine : RazorViewEngin{
        public CustomrazorViewEngine(){
            ViewLocationFormats=new string[]{
                "~/Views/{1}/{0}.cshtml",
                "~/Views/Common/{0}.cshtml"
                };
            }
        }
    }
    

    and in Global.asax

    proteced void Application_Start()
    {
        AreaRegisteration.registerAllArea();
        ViewEngines.Engines.Clear();
        ViewEngines.Engines.Add(new CustomrazorViewEngine());
        RoutConfig.registerRoutes(RouteTable.Routes);
    }
    

    I suggest doing this to prevent the Confilict of other introduced Viewengines :

    ViewEngines.Engines.Clear();