When looking over MVC code you will very often run into code snippets like below:
return RedirectToAction("Index");
<li>@Html.ActionLink("Books", "Index", "Books")</li>
where controller names, controller action names or view names as provided as hard-coded strings. This is a common practice, but is it a good practice? After all if you rename controller, and forget to rename one of many references you would get a run-time error, rather than much more preferred compile-time error.
You could likely alleviate that issue by adding static Name property to your BaseController, and then use code as follows (action names would be slightly more difficult to accomplish).
<li>@Html.ActionLink("Books", "Index", BooksController.Name)</li>
So is this hard-coding something that should be considered as a lesser evil (over not using MVC). Or did people developed some practices to work around it?
In MVC action methods are invoked via HTTP protocol. In a URL we cannot have a duplicate address or name.
A controller is responsible for controlling the way that a user interacts with an MVC application. A controller contains the flow control logic for an ASP.NET MVC application. A controller determines what response to send back to a user when a user makes a browser request.
In ASP.NET Core MVC, a controller is a class that is typically named with the suffix “Controller” and is used to define and logically group a collection of similar actions. Whenever you create a new controller, a default action method called Index is created automatically.
ASP.NET MVC Action Methods are responsible to execute requests and generate responses to it. By default, it generates a response in the form of ActionResult. Actions typically have a one-to-one mapping with user interactions.
You're looking for T4MVC, which generates strongly typed classes of string constants.
Instinctively we know that string literals are a bad thing, so your gut instinct to make "Books" a constant would normally be good. The idea is to put the string in a single location, so when you need to change "Books" to "Products", say, you only have to change it in one place.
However, in doing so, you're messing up the very tools that will help you out. I just used Resharper to rename "HomeController" to "BananaController", and it automatically updated every reference of @Html.ActionLink(... "Home" ..)
to @Html.ActionLink(... "Banana" ..)
I don't know if VS will do that without Resharper. VS is getting better at refactoring every year I'm told, but I don't actually work with anyone who doesn't have Resharper...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With