Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Shared layouts not found with overridden View paths (Location Formats) in ASP.NET MVC

I'm grouping my Views, Controllers and models. The structure is

~/Controllers
-- /_Shared
--  -- /Views
--  -- /Content
--  -- /Scripts
-- /Home
-- -- /Models
-- -- /Content
-- -- /Scripts
-- -- /Views
-- -- HomeController.cs
-- /Account
-- -- /Models
-- -- /Views
...

Views and partial views work, but layouts (master views) don't work. When I specify a layout in a .cshtml file like:

@{ Layout = "SimpleSharedLayout"; }

I get this error: The layout page "SimpleLayout" could not be found at the following path:

"~/Controllers/Account/Views/SimpleSharedLayout".

Asp.NET only searches the layout in the current controller's directory and doesn't look into the Shared folder *(which is at ~/Controllers/_Shared/Views)*

Although this works just fine.

@Html.Partial("SharedPartialView")

I have to specify layouts with full paths like

@{ Layout = "~/Controllers/_Shared/Views/SimpleSharedLayout.cshtml"; }

Which is not a hard thing to do but I'm crazy about not being able to get it working.

Using IIS Express, VS 2012, .NET 4.5

Do you have an idea about what I'm missing?

My View Engine:

public class AreaViewEngine : RazorViewEngine
{
    public AreaViewEngine()
    {
        AreaViewLocationFormats = new[] {
                         "~/Controllers/{1}/Views/{0}.cshtml",
                         "~/Controllers/_Shared/Views/{0}.cshtml"};

        ViewLocationFormats = AreaViewLocationFormats;

        AreaMasterLocationFormats = new[] { "~/Controllers/_Shared/Views/{0}.cshtml" };

        MasterLocationFormats = AreaMasterLocationFormats;

        AreaPartialViewLocationFormats = new[] { "~/Controllers/_Shared/Views/{0}.cshtml",
                         "~/Controllers/{1}/Views/{0}.cshtml"};

        PartialViewLocationFormats = AreaPartialViewLocationFormats;
    }
 }
like image 974
Seregwethrin Avatar asked Apr 01 '13 23:04

Seregwethrin


1 Answers

IMHO, you are fighting the framework's conventions. It would be my recommendation to utilize the framework in the way that it was intended with these kinds of scenarios by creating Areas.

I know it's probably not the answer you want, but I feel like what you have described is Areas to a T.

like image 63
Moby's Stunt Double Avatar answered Nov 01 '22 23:11

Moby's Stunt Double