2

I have a Controller called BaseController and Controller1 and Controller2 inherit from it.

All of the views for these controllers are under ~/Views/Base/ the reason for this is that Controller1 and 2 do the exact same thing but have custom attributes for certain things on some overriden actions.

I want to be able to point to ~/Views/Base as the location to look for views in both Controller1 and Controller2. Now can i do this without having to implement my own ViewLocator as per Dale's solution in this post Views in separate assemblies in ASP.NET MVC

I would prefer to not throw all these views into ~/Views/Shared as they aren't really shared except in between these two Controllers.

Community
  • 1
  • 1
lahsrah
  • 9,013
  • 5
  • 37
  • 67
  • Looks like the Dale's solution I liked to is deprecated. ViewLocator seems to be gone from MVC2/3. – lahsrah Jun 20 '11 at 21:59

1 Answers1

3

You could write a custom view engine in order to add this new location in the search list:

public class MyViewEngine : RazorViewEngine // WebFormViewEngine - if you are using WebForms
{
    public MyViewEngine()
    {
        ViewLocationFormats = base.ViewLocationFormats.Union(new[] 
        {
            "~/Views/Base/{0}.cshtml",
            "~/Views/Base/{0}.vbhtml",
            "~/Views/Base/{0}.aspx",
            "~/Views/Base/{0}.ascx",
        }).ToArray();
    }
}

which will be registered in Application_Start:

ViewEngines.Engines.Add(new MyViewEngine());
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • thanks. but will this mean all controllers/views will use this? Would that have any negative impact on performance. Would prefer if this didn't change my entire application's view engine like this. – lahsrah Jun 20 '11 at 06:52
  • @sylon, yes indeed, all controllers will look into this location. It won't have negative impact on performance as when running in Release mode view locations are cached by the framework. – Darin Dimitrov Jun 20 '11 at 06:53
  • I guess I will settle for this but it would be nicer if this could be specific to the controller though, if you know what I mean. Just for the sake of tidiness. – lahsrah Jun 20 '11 at 22:00