Back to: ASP.NET Core Tutorials For Beginners and Professionals
Different Ways to Generate Links in ASP.NET Core MVC
In this article, I will discuss Different Ways to Generate Links in ASP.NET Core MVC Applications with Examples. Please read our previous article discussing Creating Form Using HTML Helpers in ASP.NET Core MVC Applications with Examples.
Different Ways to Generate a Link in ASP.NET Core MVC
Creating links in ASP.NET Core MVC is essential for navigating between different parts of your web application. In ASP.NET Core MVC, links can be generated in several ways. These techniques enable you to create URLs that can lead to different parts of your application, such as controller actions, static files, or external websites. The following are some of the most common methods for generating links in ASP.NET Core MVC:
- Html.ActionLink
- Html.RouteLink
- Action Tag Helper
- Url.Action
- Url.RouteUrl
Html.ActionLink
The ActionLink is an HTML helper method used in ASP.NET Core MVC views to generate an anchor (<a>) element that links to a specific action method on a controller. The following is the syntax:
@Html.ActionLink(linkText: “Link Text”, actionName: “ActionName”, controllerName: “ControllerName”, routeValues: null, htmlAttributes: null)
Parameters:
- linkText: The text to display for the link.
- actionName: The name of the action method in the controller
- controllerName: The controller’s name (without the “Controller” suffix).
- routeValues: Any additional route parameters to pass (optional).
- htmlAttributes: HTML attributes for the anchor tag. This is optional.
Html.RouteLink
This method generates a link based on routing information rather than a specific controller and action. The following is the syntax:
@Html.RouteLink(linkText: “Link Text”, routeName: “RouteName”, routeValues: new { controller = “ControllerName”, action = “ActionName” }, htmlAttributes: null)
Parameters:
- linkText: The display text of the link.
- routeName: The name of the route.
- routeValues: Parameters such as controller, action, and additional route values.
- htmlAttributes: HTML attributes like classes, IDs, etc.
Action Tag Helper
The Action Tag Helper is a more modern approach to generating links in Razor views using Razor syntax. This helper allows you to generate links by using controller and action names, and it helps create a strongly typed link generation mechanism that reduces errors in manually specifying URLs. The following is the syntax:
<a asp-controller=”ControllerName” asp-action=”ActionName” asp-route-id=”@Model.Id”>Link Text</a>
Here,
- asp-controller: Specifies the controller.
- asp-action: Specifies the action.
- asp-route-id: Additional route parameter (e.g., an ID).
Url.Action
This generates a URL as a string, which you can use anywhere in your views or controllers. This is useful in scenarios where we need the URL rather than an anchor tag. The following is the syntax:
@Url.Action(“ActionName”, “ControllerName”, new { id = Model.Id })
Here,
- ActionName: The action method.
- ControllerName: The controller name.
- Additional route parameters can be passed using anonymous objects.
The Url.Action will only generate the URL, so additional HTML or Razor syntax is needed to create the anchor tag or other elements where the URL will be used. For example, we can use Url.Action to specify the href attribute value of an anchor tag as follows:
<a href=”@Url.Action(“ActionName”, “ControllerName”, new { id = 1 })”>Link Text</a>
Url.RouteUrl
This is similar to Url.Action, i.e., generates a URL string, but instead of specifying the action and controller, we use a route name. The following is the syntax:
@Url.RouteUrl(“RouteName”, new { id = Model.Id })
Here,
- RouteName: The name of the route.
- Additional route parameters are passed as anonymous objects.
It generates only the URL string, which can then be embedded into anchor tags or other elements. For example, we can generate an anchor element as follows:
<a href=”@Url.RouteUrl(“RouteName”, new { id = 1 })”>Link Text</a>
Example to Understand How to Generate Links in ASP.NET Core MVC:
Let’s assume we are working on a Product Management system with a Product Controller. The Product Controller has two action methods: List and Details. The List method will render a view displaying all the products Names, with each product having a link to display the product details. The Details action method will take the Product ID and render that Product information. In this example, I will show you how to generate the link with all the options in the List View. Clicking on the link will render the Details view. Let us proceed and see how to implement this step by step:
Creating the Product Model:
First, create a class file named Product.cs within the Model folder and then copy and paste the following code. This will be our model, which will hold the Product information.
namespace HTML_HELPER.Models { public class Product { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public string Category { get; set; } public decimal Price { get; set; } public int Quantity { get; set; } } }
ProductsController
Next, create an empty MVC Controller named ProductsController and copy and paste the following code. As discussed, the following Controller has two action methods. The List() action method Retrieves and displays a list of products. The Details(int id) action method Retrieves and displays the details of a specific product based on its id.
using HTML_HELPER.Models; using Microsoft.AspNetCore.Mvc; namespace HTML_HELPER.Controllers { public class ProductsController : Controller { // Static list of products, initialized with three products. // This simulates an in-memory database of products. private static readonly List<Product> _products = new List<Product> { // Defining individual Product objects with properties such as Id, Name, Description, Category, Price, and Quantity. new Product { Id = 1, Name = "Laptop", Description = "A powerful laptop.", Category = "Electronics", Price = 1200.00m, Quantity = 10 }, new Product { Id = 2, Name = "Smartphone", Description = "A high-end smartphone.", Category = "Electronics", Price = 800.00m, Quantity = 20 }, new Product { Id = 3, Name = "Desktop", Description = "A Performance Desktop", Category = "Electronics", Price = 1000.00m, Quantity = 15 } }; // This action method handles requests to the "List" action in the controller. // It returns a view displaying the list of products by passing the _products list to the view. public IActionResult List() { // Return the 'List' view and pass the _products collection to it for rendering. return View(_products); } // This action method handles requests to the "Details" action in the controller. // It accepts an 'id' parameter that is used to identify and retrieve a specific product. public IActionResult Details(int id) { // Using the List.Find method to search the _products list for a product with the matching Id. var product = _products.Find(p => p.Id == id); // Return the 'Details' view and pass the selected product to it for rendering. return View(product); } } }
Creating a Route:
Next, add the following code to the Program.cs class file. Here, we are adding a new route with the name ProductDetails. We will use this route name inside a view to generate the link.
app.MapControllerRoute( // Assigning a unique name to the route for identification purposes. // This can be used later for URL generation. name: "ProductDetails", // Defining the URL pattern that will be matched for this route. // In this case, the URL will be of the form: "Products/Details/{id}". // "{id}" is a route parameter placeholder that will capture the product's ID from the URL. pattern: "Products/Details/{id}", // Specifying default route values that will be used if none are provided in the URL. // Here, the controller is set to "Products" and the action method is set to "Details". // This means that if a request matches the "Products/Details/{id}" pattern, // it will be directed to the ProductsController's Details action method. defaults: new { controller = "Products", action = "Details" } );
Creating Views
Let’s create views for these actions and demonstrate different link-generation methods.
List View
Create the List.cshtml view and copy and paste the following code. This view displays a list of product names and uses different mechanisms to generate links. Clicking on the link will navigate to the Product details page and display that product information:
@model IEnumerable<HTML_HELPER.Models.Product> @{ ViewData["Title"] = "Product List"; } <h2 class="text-center my-4">Product List</h2> <div class="table-responsive"> <table class="table table-bordered table-striped"> <thead class="thead-dark"> <tr> <th>Name</th> <th>ActionLink</th> <th>RouteLink</th> <th>Tag Helper</th> <th>Action</th> <th>RouteUrl</th> </tr> </thead> <tbody> @foreach (var item in Model) { <tr> <td>@item.Name</td> <td> @Html.ActionLink("View", "Details", "Products", new { id = item.Id }, new { @class = "btn btn-primary btn-sm" }) </td> <td> @Html.RouteLink("View", "ProductDetails", new { id = item.Id }, new { @class = "btn btn-secondary btn-sm" }) </td> <td> <a asp-controller="Products" asp-action="Details" asp-route-id="@item.Id" class="btn btn-success btn-sm">View</a> </td> <td> <a href="@Url.Action("Details", "Products", new { id = item.Id })" class="btn btn-warning btn-sm">View</a> </td> <td> <a href="@Url.RouteUrl("ProductDetails", new { id = item.Id })" class="btn btn-info btn-sm">View</a> </td> </tr> } </tbody> </table> </div>
Details View
Next, create the Details.cshtml view. This view displays a product’s details. The DisplayNameFor helper methods display the model’s property name, and the DisplayFor method displays the associated value of the property.
@model HTML_HELPER.Models.Product @{ ViewData["Title"] = "Product Details"; } <div class="container mt-4"> <h4 class="mb-3">Product Details</h4> <div class="card"> <div class="card-body"> <dl class="row"> <dt class="col-sm-4">ID:</dt> <dd class="col-sm-8"> @Html.DisplayFor(model => model.Id) </dd> <dt class="col-sm-4">Name:</dt> <dd class="col-sm-8"> @Html.DisplayFor(model => model.Name) </dd> <dt class="col-sm-4">Description:</dt> <dd class="col-sm-8"> @Html.DisplayFor(model => model.Description) </dd> <dt class="col-sm-4">Category:</dt> <dd class="col-sm-8"> @Html.DisplayFor(model => model.Category) </dd> <dt class="col-sm-4">Price:</dt> <dd class="col-sm-8"> @Html.DisplayFor(model => model.Price) </dd> <dt class="col-sm-4">Quantity:</dt> <dd class="col-sm-8"> @Html.DisplayFor(model => model.Quantity) </dd> </dl> </div> </div> </div> <div class="text-center mt-4"> <a asp-action="List" asp-controller="Products" class="btn btn-primary">Back to List</a> </div>
Now, run the application and navigate to the Products/List URL, and you should see the following page:
Now, if you click any of the links on the above page, then it should open the Details Page as shown in the below image:
Differences Between Html.ActionLink, Html.RouteLink, Action Tag Helper, Url.Action, Url.RouteUrl in ASP.NET Core MVC
The following are the key differences between Html.ActionLink, Html.RouteLink, Action Tag Helper, Url.Action, and Url.RouteUrl in ASP.NET Core MVC:
Html.ActionLink
- Purpose: Generates an HTML <a> element that links to a specified action method on a controller.
- Routing: Relies on the default MVC routing based on controller and action names.
- Usage: Typically used in Razor views when we want to generate an anchor link directly to a controller’s action.
- Return Type: Returns an anchor (<a>) tag with the URL embedded in the href attribute.
Html.RouteLink
- Purpose: Generates an HTML <a> element, but based on route names rather than directly specifying controller and action names.
- Routing: Relies on custom routes defined in the Program.cs class file.
- Usage: It is useful when we have custom routes and need to generate links that use those routes rather than hardcoding controller/action names.
- Return Type: Returns an anchor (<a>) tag with the URL based on the route name.
Action Tag Helper
- Purpose: Generates an anchor (<a>) tag using Razor syntax and tag helpers, which are easier to read and maintain.
- Routing: Relies on the default MVC routing based on controller and action names, similar to Html.ActionLink.
- Usage: Modern, declarative approach to creating links in Razor views.
- Return Type: Returns an anchor (<a>) tag with the URL embedded in the href attribute, automatically generated using the specified controller/action.
Url.Action
- Purpose: Generates a URL string (not an anchor tag) to a specific action method on a controller.
- Routing: Similar to Html.ActionLink, relies on default MVC routing.
- Usage: Used when we need a URL string to be used dynamically, such as when manually constructing HTML elements.
- Return Type: Returns a URL string pointing to the specified action.
Url.RouteUrl
- Purpose: Generates a URL string based on route names or custom routes rather than specifying controller and action names.
- Routing: Uses custom routes defined in the routing configuration.
- Usage: Similar to Url.Action, but works with custom routing or named routes.
- Return Type: Returns a URL string based on the route name.
Choosing the Right Approach:
- Use Html.ActionLink: When you need simple anchor links based on action/controller.
- Use Html.RouteLink: When you are working with named/custom routes and need a link.
- Use Action Tag Helper: For modern, cleaner link generation in Razor pages.
- Use Url.Action: When you need the URL as a string for JavaScript or other dynamic uses.
- Use Url.RouteUrl: When you need the URL as a string but based on custom routes or named routes.
In the next article, I will discuss Tag Helpers in ASP.NET Core MVC Application with Examples. In this article, I explain Different Ways to Generate Links in ASP.NET Core MVC Applications with Examples. I hope you enjoy this “Different Ways to Generate Links in ASP.NET Core MVC” article.