Html.ActionLink in ASP.NET MVC


What is ActionLink?

Html.ActionLink is an HTML Helper in ASP.NET MVC used to create a hyperlink (anchor tag).

When the user clicks the link, it calls a specific Controller Action Method.


Simple Definition

ActionLink creates a clickable link that redirects to another Controller and Action.


Basic Syntax

@Html.ActionLink("LinkText","ActionName","ControllerName")

Real-Life Example

Imagine a website menu:

  • Home
  • Students
  • Departments

Each menu item is created using ActionLink to navigate between pages.


Why Use ActionLink?

  • Automatically generates correct URL
  • Works with routing system
  • No need to hard-code URLs
  • Safe and clean navigation

Summary

✔ ActionLink creates hyperlink
✔ Connects View to Controller Action
✔ Supports parameters
✔ Supports CSS styling
✔ Works with MVC routing


What We Are Going To Do in This Example:

In this example, we are going to learn how to use the ActionLink HTML Helper in ASP.NET MVC.

Our goal is simple:

  • Display a list of employees
  • Show employee names in bulleted format
  • Make each employee name a clickable hyperlink

When the user clicks on an employee name:

  • The request will go to EmployeeController
  • The Details action method will execute
  • The selected employee’s details page will open

So basically, we are connecting the View to the Controller using ActionLink.

This is what we are going to implement step by step in our example.


Run the SQL Script

Below, the SQL script is provided.

Important Instructions:

  1. Open SQL Server Management Studio (SSMS).
  2. Connect to your SQL Server.
  3. Click on New Query.
  4. Copy the complete SQL code given below.
  5. Paste it into the New Query window.
  6. Click Execute (or press F5).

After running the script, the Database, Tables, and Sample Data will be created automatically.

That’s it — everything will be ready for use in your MVC project.


CREATE DATABASE MVC_ActionLink;
GO

USE MVC_ActionLink;
GO

-- Create Employee Table
CREATE TABLE Employee
(
    Id INT PRIMARY KEY IDENTITY(1,1),
    Name NVARCHAR(50),
    Gender NVARCHAR(10),
    City NVARCHAR(50),
    Salary DECIMAL(18,2),
    DateOfBirth DATETIME
);
GO

-- Insert test data into Employee table
INSERT INTO Employee (Name, Gender, City, Salary, DateOfBirth)
VALUES
('Khushbu','Female', 'Aurangabad', 10000, '1995-06-15'),
('Ayaan','Male',   'Hyderabad', 5000, '1992-04-10'),
('Sara','Female', 'Bangalore', 4500, '1994-01-22'),
('Zaid','Male',   'Delhi', 6000, '1991-08-18'),
('Fatima','Female', 'Pune', 5500, '1993-03-05'),
('Rehan','Male',   'Chennai', 4800, '1990-11-12'),
('Iqra','Female', 'Kolkata', 5200, '1996-09-09'),
('Arman','Male',   'Jaipur', 4700, '1992-07-14'),
('Hiba','Female', 'Lucknow', 5100, '1994-12-30');
GO

-- Stored Procedure to retrieve all employees
CREATE PROCEDURE spGetAllEmployees
AS
BEGIN
    SELECT Id, Name, Gender, City, Salary, DateOfBirth
    FROM Employee;
END;
GO

Step 1: Create New Project

  • Open Visual Studio
  • Click Create New Project
  • Select ASP.NET Web Application (MVC)
  • Click Create

Step 2: Connect Database

  • Right Click on Project Name
  • Select Add → New Item
  • Choose Data
  • Select ADO.NET Entity Data Model
  • Click Add
  • Connect to your Database
  • Select required Tables
  • Click Finish

After this, Model Classes and DbContext will be AUTO-GENERATED.


Create Employee Controller

In the previous example, we created a class inside the Models folder.

But in this new example, we will create a Controller instead.

Go to the Controllers folder 📁, right-click on it, and select Add → Controller.

Choose MVC 5 Controller – Empty and click Add.

Name the controller EmployeeController and click Add.

After creating the controller, open EmployeeController.cs .

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Your_Project_Name.Controllers
{
    public class EmployeeController : Controller
    {
        public ActionResult Index()
        {
            MVC_ActionLinkEntities dbContext = new MVC_ActionLinkEntities();

            List<Employee> empList = dbContext.Employees.ToList();

            return View(empList);
        }

        public ActionResult Details(int id)
        {
            MVC_ActionLinkEntities dbContext = new MVC_ActionLinkEntities();

            Employee employee = dbContext.Employees.FirstOrDefault(x => x.Id == id);

            return View(employee);
        }
    }
}

Create Index View (Empty Template)

Now open EmployeeController.

Right-click on the Index action method → Select Add View.

Choose MVC 5 View.


Configure the Add View options:

  • View Name: Index
  • Template: Empty (without model)
  • Model Class: Blank
  • Data Context Class: Blank

Then click the Add button.

Important:

After the Index.cshtml file is created, delete any existing code (if present).

Now copy the code given below and paste it inside Views → Employee → Index.cshtml.

@model IEnumerable<Your_Project_Name.Employee>
@using Your_Project_Name;

<div style="font-family:Arial">

    @{
        ViewBag.Title = "Employee List";
    }

    <h2>Employee List</h2>

    <ul>

        @foreach (Employee employee in Model)
        {
            <li>
                @Html.ActionLink(employee.Name,"Details",new { id = employee.Id })
            </li>
        }

    </ul>

</div>

Create Details View for Employee

Now open EmployeeController.

Right-click on the Details action method → Select Add View.

Choose MVC 5 View.


Configure the Add View options carefully:

  • View Name: Details
  • Template: Details
  • Model Class: Employee (WebApplication7)
  • Data Context Class: MVC_ActionLinkEntities (WebApplication7)

Then click the Add button.

Visual Studio will automatically generate the Details.cshtml file.

Now run the project and click on any Employee name — the Employee Details page will open successfully.

@model Your_Project_Name.Employee

@{
    ViewBag.Title = "Details";
}

<h2>Details</h2>

<div>
    <h4>Employee</h4>
    <hr />

    <dl class="dl-horizontal">

        <dt>
            @Html.DisplayNameFor(model => model.Name)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Name)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Gender)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Gender)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.City)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.City)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.Salary)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.Salary)
        </dd>

        <dt>
            @Html.DisplayNameFor(model => model.DateOfBirth)
        </dt>

        <dd>
            @Html.DisplayFor(model => model.DateOfBirth)
        </dd>

    </dl>
</div>

<p>
    @Html.ActionLink("Edit", "Edit", new { id = Model.Id }) |
    @Html.ActionLink("Back to List", "Index")
</p>

Update RouteConfig.cs

Open the RouteConfig.cs file.

By default, the route is set to:

defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }

I have changed "Home" to "Employee".

Now the updated code will be:

defaults: new { controller = "Employee", action = "Index", id = UrlParameter.Optional }

Important:

When you run the project, it will directly open the Employee Controller instead of the Home Controller.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;

namespace Your_Project_Name
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new 
                { 
                    controller = "Employee",action = "Index",id = UrlParameter.Optional 
                }
            );
        }
    }
}

Output



Application URL

https://localhost:44369/Employee/Index