Search code examples
asp.net-mvcpathviewareas

.net MVC proper way to link to views within an area


I have a .Net MVC app with a couple areas, one of which is called Admin. When I execute /Admin/Home/Index, the Index() method in the Admin area Home controller executes and the correct Index.cshtml is returned. So far, so good.

My issue is related to _Layout.cshtml. I want the layout to be different for each area and for the main site. To that end I have added _ViewStart.cshtml to my Admin area's Views folder, and within that _ViewStart I have the following:

@{ Layout = "/Areas/Admin/Views/Shared/_Layout.cshtml"; }

Again, so far, so good, but using a fully qualified path seems inelegant and I have to think there is a better way.

A similar question was asked here:

Area doesn't use the right view

The one answer that was given says that the fully qualified path is the way to go, though it was not marked as the answer by the OP.

So my question is this. Is it necessary to use a fully qualified path to reference views within an area? Is it not possible to do this in an area:

@{ Layout = "~/Views/Shared/_Layout.cshtml"; }

Based on the controller that is executing, is the view engine not capable of resolving that I want the view from the area's shared folder and not the view from the main site's shared folder?

Thanks, Chris


Solution

  • Your Views inside of the Areas will automatically look to the Views folder in that area for a _ViewStart.cshtml or a _ViewImports.cshtml file. My advice in your case would be to put a _ViewStart.cshtml file into your Area's View folders (Not in their Shared folders!) and have it reference the _Layout file of your choice such as:

    _ViewStart.cshtml

    @{
        Layout = "_Layout";
    }