Is it ok to put controller name as string?

Viewed 105

I was wondering if is it OK to put the controller name as a string, like in the following example. Also, should I put the action as a string instead? Is there any better approach? My concert is that if I change the controller's name for any reason, my best option is to do a "find-replace" in the whole project as it is now. example1

Many thanks!

2 Answers

Yes, that is exactly how you use the anchor tag helpers. At least to me that asp-action seems convoluted and I would simply have written it as:

  <a asp-controller="Operation" asp-action="Index">...</a>

If you do change your controller name (which should not happen very often), then you would have to update the links.

For further reference see https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/built-in/anchor-tag-helper?view=aspnetcore-3.1: "If the asp-controller attribute is specified and asp-action isn't, the default asp-action value is the controller action associated with the currently executing view. [...] If the asp-action attribute value is Index, then no action is appended to the URL, leading to the invocation of the default Index action. The action specified (or defaulted), must exist in the controller referenced in asp-controller."

In general, we directly use the name of the controller and action as strings, as shown below:

(However, this wording cannot be changed automatically after you change the controller name, you need to modify manually)

<a class="nav-link text-dark" asp-controller="Operation" asp-action="Index"> </a>

1. According to your current wording, you can update the code as follows:

(This will change dynamically as you change the name of the controller)

<a class="nav-link text-dark" asp-controller="@nameof(OperationController).Replace("Controller","")"  asp-action="@nameof(OperationController.Index)"> link </ a>

2. As an alternative solution, you can add the Route attribute to the action specified by the a tag and set the route name.

In the a tag, you only need to use asp-route to link the corresponding action.

Please refer to this.

 <a class="nav-link text-dark" asp-route="MyRouteName"> link </a>

Controller:

 public class OperationController: Controller
        {
            [Route ("CustomControllerName/Index", Name="MyRouteName")]
            public IActionResult Index ()
            {
                return View ();
            }
        }
Related