0

I have a number of shared views in a C# asp.net MVC Core web application. The shared views contain generated links using tag-helpers asp-controller=..., which need to link back to the controller which routed the view. If the page is from the admin controller, the links need to point to the route on the admin controller. If the page is from the user controller, the links need to point to the route on the user controller.

I could hard-code the controller name in a const public const string _controllerName = "Admin";, but this would require modifying the constant if the controller name were changed.

I could map the controller name in every single route in the controller, but this seems very inefficient. I'd like to grab the controller name during construction, and store it in a property of the controller itself, to pass to the ViewModels to affect the links generated in the shared views. (ControllerContext.RouteData is not available during controller construction).

Is there a way to get the name of the controller during controller construction? Or, alternatively, is there a way to get links from shared views to direct back to the controller than generated them?

Example link:

<a asp-controller="@Model.ControllerString" asp-action="Computer" asp-route-name="@computer.Position">Computer @computer.Position</a>

JamesDuff
  • 413
  • 1
  • 4
  • 8

0 Answers0