views:

106

answers:

1

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();
        }
+1  A: 

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;  
    }
Craig Stuntz
I love you! :D
Arnis L.
Now just need to tweak this with filter for controllers - something like [AddPartialViewLocation("Shared/SuperFolder")]. How do you think - it's a good/bad idea?
Arnis L.
I would probably use an IDictionary<Type, IEnumerable<string>>. Then you could get an enumerable list of paths to probe for any arbitrary number of controller types. The method above would check to see if the current controller type is in the dictionary (w/ TryGetValue), then probe the paths for that type in order if found.
Craig Stuntz
Seems that you agree that this isn't a bad idea. Thanks for some implementation ideas.
Arnis L.
It's not a bad idea within limits. We do it, for instance, to serve special views for mobile phone devices, but the same rule applies for all controllers. If every controller had a different probing path for views, however, that could be quite confusing for people trying to maintain your project. In our case, I'm betting that any developer who sees a "Mobile" subfolder in the views can figure out what it's for. So choose your rules carefully!
Craig Stuntz
Recently - had some problems with this. Just like with some others customizations. But after all - wasn't so bad and I like it. Really flexible.
Arnis L.