Search code examples
asp.net-mvcdirectorypartial-viewsviewengine

How to group partial shared views for specified controllers?


Is it possible to tell ViewEngine to look for partial shared views in additional folders for specified controllers (while NOT for others)?

I'm using WebFormViewEngine.

This is how my PartialViewLocations looks at the moment.

 public class ViewEngine : WebFormViewEngine
    {
        public ViewEngine()
        {
            PartialViewLocationFormats = PartialViewLocationFormats
                .Union(new[]
                       {
                           "~/Views/{1}/Partial/{0}.ascx",
                           "~/Views/Shared/Partial/{0}.ascx"
                       }).ToArray();
        }

Solution

  • Sure. Don't change PartialViewLocationFormats in this case; instead, do:

        public override ViewEngineResult FindPartialView(
            ControllerContext controllerContext, 
            string partialViewName, 
            bool useCache)
        {
            ViewEngineResult result = null;
    
            if (controllerContext.Controller.GetType() == typeof(SpecialController))
            {
                 result = base.FindPartialView(
                     controllerContext, "Partial/" + partialViewName, useCache);
            }
    
            //Fall back to default search path if no other view has been selected  
            if (result == null || result.View == null)
            {
                result = base.FindPartialView(
                    controllerContext, partialViewName, useCache);
            }
    
            return result;  
        }