asp.net-corerazor-pagesasp.net-mvc-areas

How to use RedirectToPage to navigate to a page in another area


RedirectToPage("Companies") will redirect to /Pages/Companies.cshtml (from an MVC controller)

But what if want redirect to this page /Areas/MyArea/Pages/Companies.cshtml?

All those and many others don't work:

RedirectToPage("/MyArea/Companies.cshtml") 
RedirectToPage("MyArea/Companies.cshtml") 
RedirectToPage("./MyArea/Companies.cshtml") 
RedirectToPage("/MyArea/Companies") 
RedirectToPage("MyArea/Companies") 
RedirectToPage("./MyArea/Companies") 

Sometimes I get a "Page not found" error. Sometimes I get the message "Specify a root relative path with a leading '/' to generate a URL outside of a Razor Page". There are no Pages folder. I know all this can change all rules again.

My Razor pages are configured with .SetCompatibilityVersion(CompatibilityVersion.Version_2_1);... no specific routing added.


Solution

  • Use the overload of RedirectToPage that takes an object representing RouteValues:

    return RedirectToPage("/Companies", new { area = "MyArea" });
    

    Note that the '/' is required if you use RedirectToPage in a controller (or anywhere outside of a Razor Page). Otherwise it is not required (but will still work).