Search code examples
c#asp.netrazor-pagesasp.net5

Sharing pages between different Razor Page areas


I wonder if I could get some ideas on how best to approach this.

I have a Razor Pages application. I have several areas, and each area has its own layout page and menus.

This is pretty straight forward, but I have a couple of pages I need to share with two or more areas. These shared pages will be passed an argument that indicates which area it's being used by, and I would want the layout page (menu) for that page to be the one for that area. (Ideally, the URL would also reflect the current area.)

I'm not sure if this is practical. I'd like to keep things as simple as possible. But all I come up with is some fairly complex routing stuff.


Solution

  • Two options I can think of:

    1. Put the shared page in the root Pages folder and use AddPageRoute to add multiple routes to the shared page including a parameter for the area name:

      options.Conventions.AddPageRoute("/SharedPage", "{areaName}/alias1"); options.Conventions.AddPageRoute("/SharedPage", "{areaName}/alias2");

    You can set the layout based on the value of RouteData.Values["areaName"]. Don't use area as the parameter name. It's a reserved word as far as routing is concerned:

     @{
        if(RouteData.Values["areaName"] == "foo")
        {
             Layout = "_FooLayout";
        }
        if(RouteData.Values["areaName"] == "bar")
        {
             Layout = "_BarLayout";
        }
     }
    
    1. Add pages to the areas that act as placeholders to generate the routes, and then extract the body of the shared page to a partial that can be placed in the top level Pages/Shared folder so that it is accessible to all other pages in the application. If you want to centralise some of the processing for the shared page, create a class that inherits from PageModel and put your processing logic there, then have the actual PageModel classes inherit from that.