Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET Core 2: how to RedirectToPage with area?

RedirectToPage("Companies") will redirect to /Pages/Companies.cshtml (from an ASP.NET 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 "Page not found" error. Sometimes get "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.

P.S. Razor pages configred with plain .SetCompatibilityVersion(CompatibilityVersion.Version_2_1); no specific routing added.

like image 974
Roman Pokrovskij Avatar asked Aug 31 '18 02:08

Roman Pokrovskij


People also ask

What is MVC core area?

Areas are an ASP.NET feature used to organize related functionality into a group as a separate namespace (for routing) and folder structure (for views). Using areas creates a hierarchy for the purpose of routing by adding another route parameter, area , to controller and action or a Razor Page page .

How do I redirect a page in razor?

You can use the IActionResult to return a redirection or your razor page.

How do I add a new controller in NET Core?

Select the EXPLORER icon and then control-click (right-click) Controllers > New File and name the new file HelloWorldController. cs . In Solution Explorer, right-click Controllers > Add > New File. Select ASP.NET Core and Controller Class.


1 Answers

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).

like image 150
Mike Brind Avatar answered Oct 29 '22 00:10

Mike Brind