Different Ways to Generate Links in ASP.NET Core MVC

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. Creating links in ASP.NET Core MVC is essential for navigating between different parts of your web application.

Different Ways to Generate a Link in ASP.NET Core MVC

In ASP.NET Core MVC, generating links is a common task that can be achieved 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. Here 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

Html.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. 

Syntax: Html.ActionLink(“Link Text”, “ActionName”, “ControllerName”, new { id = “Parameter” }, new { @class = “cssClass” })

  • “Link Text”: The text to display for the link.
  • “ActionName”: The name of the action method in the controller.
  • “ControllerName”: The name of the controller (without the “Controller” suffix).
  • new { id = “Parameter” }: Route values for the action method parameters. This is optional.
  • new { @class = “cssClass” }: HTML attributes for the anchor tag. This is optional.

When to use: Generates a hyperlink to an action method by using the action name and controller name. Use Html.ActionLink when you need to generate a straightforward link to an action method from within a Razor view. It’s useful when the link text and the action are straightforward to define inline.

Html.RouteLink

The Html.RouteLink method is one of the ways to generate links to different routes within your application. This method is especially useful when you want to generate a link based on route name and parameters rather than controller and action names directly.

Syntax: @Html.RouteLink(“Link Text”, “RouteName”, new { id = 1 }, new { @class = “css-class” })

Here,

  • “Link Text” is the display text for the link.
  • “RouteName” is the name of the route.
  • The third parameter is for route values. This is optional.
  • The fourth parameter is for HTML attributes. This is optional.

When to use: Generates a hyperlink based on a route name and route values. Use Html.RouteLink when you have complex routing requirements that cannot be easily addressed by specifying action and controller names alone. It is particularly useful when you want to generate a link that adheres to a specific routing configuration defined in your Program.cs.

Action Tag Helper

Creating links in ASP.NET Core MVC applications can be easily managed using Tag Helpers, specifically the Anchor Tag Helper. 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 asp-action and asp-controller tag helpers can be used to generate links.

Syntax: <a asp-action=”ActionName” asp-controller=”ControllerName” asp-route-id=”1″ class=”css-class”>Link Text</a>

Here,

  • asp-action specifies the action method.
  • asp-controller specifies the controller.
  • asp-route-id specifies the route data (if any).
  • class is a standard HTML attribute for CSS styling.

When to use: An HTML tag helper that generates a hyperlink to an action method. Use the Action Tag Helper when working with Razor Pages or MVC views where you prefer to work with HTML-like syntax instead of the Razor HTML helpers. Tag helpers are generally preferred for their clarity and HTML-friendly approach.

Url.Action

Generates a URL string to an action method. This is useful in scenarios where you need the URL itself rather than an anchor tag. It 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. The Url.Action can be used within Razor views to generate URLs, which can then be embedded into anchor tags or other elements as needed.

Syntax: <a href=”@Url.Action(“ActionName”, “ControllerName”, new { id = 1 })” class=”css-class”>Link Text</a>

Here,

  • <a>: This is the HTML anchor tag used to create hyperlinks. Anything enclosed between the opening <a> and closing </a> tags becomes clickable and can navigate the user to another view or website.
  • href=: This attribute within the anchor tag specifies the URL to which the link should navigate when clicked.
  • @Url.Action(…): This is a Razor syntax feature used within an ASP.NET Core MVC view. It invokes the Url.Action method, which generates a URL to an action method within a controller.
  • “ActionName”: The first parameter specifies the name of the action method you want to link to. This action method should exist within the specified controller and be responsible for returning a view or performing some operations when the link is clicked.
  • “ControllerName”: The second parameter is the name of the controller where the action method resides. Controllers in ASP.NET Core MVC serve as an intermediary between models and views, handling user inputs and returning responses.
  • new { id = 1 }: This is an anonymous object that represents route values. Here, it specifies any additional parameters that the action method requires. In this example, an id parameter with a value of 1 is passed to the action method. This is useful for specifying which resource you want to access or manipulate when the link is clicked.
  • class=”css-class”: This is a standard HTML attribute that applies CSS classes to the anchor tag. In this example, “css-class” is a placeholder for whatever CSS class you want to apply to style the link.
  • Link Text: This is the visible text of the hyperlink that users see on the web page. When clicked, it will navigate the user to the URL specified in the href attribute.

When to use: Use Url.Action when you need to generate a URL to an action method but don’t necessarily want to render it as a hyperlink at that moment. This is useful for scenarios like passing URLs to JavaScript for AJAX calls or when setting the src attribute of an <img> tag dynamically.

Url.RouteUrl

Generates a URL string that corresponds to a route defined in the routing configuration. It generates only the URL, requiring additional syntax to incorporate the URL into an HTML element. The Url.RouteUrl can be used within Razor views to generate URLs, which can then be embedded into anchor tags or other elements as needed.

Syntax: <a href=”@Url.RouteUrl(“RouteName”, new { id = 1 })” class=”css-class”>Link Text</a>

Here,

  • <a>: This is the HTML anchor tag, used to define hyperlinks that, when clicked, will navigate the user to the specified URL.
  • href=: This attribute within the anchor tag specifies the URL the link points to.
  • @Url.RouteUrl(…): This is a Razor syntax feature within an ASP.NET Core MVC view. It calls the Url.RouteUrl method to generate a URL to a route defined in the routing configuration of the ASP.NET Core MVC application.
  • “RouteName”: The first parameter is the name of the route you want to generate a URL for. This route name must match one of the named routes defined in your application’s route configuration.
  • new { id = 1 }: The second parameter is an anonymous object that specifies route values. In this case, it provides a route value id with the value of 1. This is used to populate parameters in the route’s template.
  • class=”css-class”: This is a standard HTML attribute used to apply CSS classes to the anchor tag. It allows you to style the link using CSS. “css-class” is a placeholder for whatever CSS class you wish to apply.
  • Link Text: This is the text displayed for the hyperlink on the web page. Users can click on this text to follow the link generated by @Url.RouteUrl.

When to use: Use Url.RouteUrl when you need to generate a URL that adheres to a specific routing configuration, similar to Html.RouteLink, but without immediately rendering it as a hyperlink. This is useful for more complex routing scenarios where you need the URL for purposes other than directly linking, such as in AJAX calls or other dynamic client-side operations.

Example to Understand How to Generate Links in ASP.NET Core MVC:

Let us see an example of the above-discussed approaches to generate links in ASP.NET Core MVC Views. First, create a class file named Product.cs within the Model folder and then copy and paste the following code:

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

Let’s assume we have a Products controller with two actions: List (to display a list of products) and Details (to display details of a specific product). We want to create links in our views that direct users to these actions. So, create an empty MVC Controller named ProductsController and then copy and paste the following code:

using HTML_HELPER.Models;
using Microsoft.AspNetCore.Mvc;

namespace HTML_HELPER.Controllers
{
    public class ProductsController : Controller
    {
        private static readonly List<Product> _products = new List<Product>
        {
            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 }
        };

        public IActionResult List()
        {
            return View(_products);
        }

        public IActionResult Details(int id)
        {
            var product = _products.Find(p => p.Id == id);
            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(
    name: "ProductDetails",
    pattern: "Products/Details/{id}",
    defaults: new { controller = "Products", action = "Details" });

Creating Views

Now, let’s create views for these actions and demonstrate different link-generation methods.

List View (List.cshtml)

This view displays a list of product names and uses different mechanisms to generate links to the details of each product:

@model IEnumerable<HTML_HELPER.Models.Product>

@{
    ViewData["Title"] = "List";
}

<h2>Product List</h2>

<table class="table">
    <thead>
        <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 = "product-link" })
                </td>
                <td>
                    @Html.RouteLink("View", "ProductDetails", new { id = item.Id }, new { @class = "link-class" })
                </td>
                <td>
                    <a asp-controller="Products" asp-action="Details" asp-route-id="@item.Id" class="link-class">View</a>
                </td>
                <td>
                    <a href="@Url.Action("Details", "Products", new { id = item.Id  })" class="link-class">View</a>
                </td>
                <td>
                    <a href="@Url.RouteUrl("ProductDetails", new { id = item.Id })" class="link-class">View</a>
                </td>
            </tr>
        }
    </tbody>
</table>
Details View (Details.cshtml)

This view displays the details of a single product. The DisplayNameFor helper methods display the model property’s name, and the DisplayFor method displays the associated value of a model property.

@model HTML_HELPER.Models.Product

@{
    ViewData["Title"] = "Details";
}

<div>
    <h4>Product Details</h4>
    <hr />
    <dl class="row">
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Id)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Id)
        </dd>
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Name)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Name)
        </dd>
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Description)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Description)
        </dd>
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Category)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Category)
        </dd>
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Price)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Price)
        </dd>
        <dt class = "col-sm-2">
            @Html.DisplayNameFor(model => model.Quantity)
        </dt>
        <dd class = "col-sm-10">
            @Html.DisplayFor(model => model.Quantity)
        </dd>
    </dl>
</div>
<div>
    <a asp-action="List">Back to List</a>
</div>

Now, run the application and navigate to the Products/List URL, and you should see the following page:

Different Ways to Generate Links in ASP.NET Core MVC Applications with Examples

Now, if you click any of the links, 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

Differences Between Html.ActionLink, Html.RouteLink, Action Tag Helper, Url.Action, Url.RouteUrl

ASP.NET Core MVC offers various mechanisms to generate links in views, each with its specific use case and flexibility level. Understanding the differences between these mechanisms can help you choose the most appropriate one for your needs. Here’s an overview:

Html.ActionLink

Generates a fully qualified URL to an action method by using the specified action name and controller name.

  • Syntax: @Html.ActionLink(“Link Text”, “ActionName”, “ControllerName”)
  • Pros: Easy to use for generating links to controller actions directly from Razor views. It also allows setting HTML attributes directly.
  • Cons: Less flexible compared to using tag helpers because it requires specifying parameters as method arguments, which can be error-prone if there are many parameters or route values.
Html.RouteLink

Generates a hyperlink (anchor tag) that corresponds to a route defined in the routing configuration.

  • Syntax: @Html.RouteLink(“Link Text”, “RouteName”, new { id = 1 })
  • Pros: Offers more control over the generated URL by allowing you to specify a route name and route values. It’s useful when you want to link to a specific route rather than an action method.
  • Cons: Like Html.ActionLink, specifying parameters as method arguments can be less intuitive compared to using tag helpers.
Action Tag Helper

A newer, more flexible way to generate links using tag helpers. You specify the action and controller names directly as attributes of an <a> tag.

  • Syntax: <a asp-action=”ActionName” asp-controller=”ControllerName”>Link Text</a>
  • Pros: Integrates directly into HTML, making the code more readable and maintainable. Allows for the use of ASP.NET Core’s tag helpers, which can provide IntelliSense in supported IDEs.
  • Cons: Requires understanding of tag helpers and how they work in ASP.NET Core. May not be as straightforward for developers used to traditional HTML or Razor syntax.
Url.Action

Generates a URL string to an action method. Useful in scenarios where you need the URL itself rather than an anchor tag.

  • Syntax: @Url.Action(“ActionName”, “ControllerName”)
  • Pros: Provides flexibility in generating URLs for use in various contexts, not just for anchor tags. Can be used in JavaScript or for redirect purposes.
  • Cons: Only generates the URL, so additional HTML or Razor syntax is needed to create the anchor tag or other elements where the URL will be used.
Url.RouteUrl

Generates a URL string that corresponds to a route defined in the routing configuration.

  • Syntax: @Url.RouteUrl(“RouteName”, new { id = 1 })
  • Pros: Similar to Url.Action but provides more control over the generated URL by specifying a route name and values. Useful for generating URLs based on routing rather than controller actions.
  • Cons: As with Url.Action, it generates only the URL, requiring additional syntax to incorporate the URL into an HTML element.
Conclusion

The choice between these mechanisms depends on your specific scenario:

  • Use Html.ActionLink or Html.RouteLink for straightforward link generation within Razor views when you want to include the anchor tag directly with minimal fuss.
  • Use Action Tag Helper when you prefer a more HTML-like syntax and the flexibility of tag helpers.
  • Choose Url.Action or Url.RouteUrl when you need the URL for purposes other than directly creating an anchor tag, such as generating links in scripts or for redirects.

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.

Leave a Reply

Your email address will not be published. Required fields are marked *