views:

34

answers:

3

Create a controller:

public abstract class MyBaseController : Controller
{
   public ActionResult MyAction(string id)
   {
      return View();
   }
}

Than create another specific controller that inherit from MyBaseController:

public class MyController : MyBaseController 
{

}

There is a view called MyAction.aspx in the Views/MyBaseController folder Then, call MyController/MyAction method. Following exception will be generated:

The view 'MyAction' or its master could not be found. The following locations were searched: ~/Views/MyController/PhConnect.aspx ~/Views/MyController/PhConnect.ascx ~/Views/Shared/MyAction.aspx ~/Views/Shared/MyAction.ascx

Can I make MVC.NET to use the view from Views/MyBaseController folder?

A: 

You need to add it to shared because you are in the context of the subcontroller. If you want different behavior for different controllers, then you'll want to put a MyAction view in each of your subcontroller view folders.

To answer your question though, you probably could make it look in base controller folder, but it would require you to write your own request handler which looks in base controller folders. The default implementation only looks in the view folder for the current controller context, then it looks in the shared folder. It sounds like your view is shared however, so the shared folder seems like a good place for it anyway.

NickLarsen
Thanks for reply. How I can override behavior of my controller in order to find view in base controller folders?
Egor4eg
@Egor4eg: Just set `ViewLocationFormats` on your existing ViewEngine.
bzlm
A: 

It is possible, but not very clean.

public class MyController : MyBaseController 
{
   public ActionResult MyAction(string id)
   {
       return View("~/Views/MyBaseController/MyAction.aspx");
   }
}

However if your View (MyAction.aspx) contains a reference to a Partial View, ASP.NET MVC will look for it in the Views/MyController folder (and not find it there!).

If your view is shared across controllers, its best to place it in the Views/Shared folder as recommended by NickLarsen.

Preets
A: 
Horacio Nuñez
No need to subclass - you can just set the search paths for Views on an existing View Engine by setting `ViewLocationFormats`.
bzlm
Why the downvote? The code is intended to work with every abstract inheritance chain, not just one that is hard coded.
Horacio Nuñez