I am converting some MVC example code to use in a Razor pages application I am building. In the original MVC code, some of the links use the following asp helpers (for instance):
<a asp-controller="Home" asp-action="Preview" asp-route-id="option">A link</a>
In the original MVC code there is a HomeController
controller class defined.
I can get this to work in my Razor pages app if I have a page called 'Preview' in a directory called 'Home' under the 'Pages' folder. I then map the route using the @pages directive putting
@page "{option}"
at the top of the 'Preview.cshtml' page and passing a string to the OnGet
method in the class definition of PreviewModel
in the Preview.cshtml.cs file.
This works OK but is it what I should be doing? There is no HomeController
in the Razor pages application, so is there a best practice Razor pages way of doing this?
You can't rely on the combination of the controller and action to always generate the correct route. You should change the tag helper to use the asp-page attribute instead.
<a asp-page="/Home/Preview" asp-route-id="option">A link</a>
See more about routing in Razor Pages here (my site): https://www.learnrazorpages.com/razor-pages/routing