In this article, we will discuss about generating hyperlinks using actionlink HTML helper for navigation between MVC pages.
For example, you want to display all the employees in a bulletted list as shown below. Notice that all the employee names are rendered as hyperlinks.
When the hyperlink is clicked, the user will be redirected to employee details page, displaying the full details of the employee as shown below:
Copy and paste the following Index() action method in EmployeeController class. This method retrieves the list of employees, which is then passed on to the view for rendering:
public ActionResult Index()
{
EmployeeContext employeeContext = new EmployeeContext();
List<Employee> employees = employeeContext.Employees.ToList();
return View(employees);
}
At the moment, you don't have a view that can display the list of employees. To add the view, follow this instruction:
1. Right click on the Index() action method
2. Set
- View name = Index
- View engine = Razor
Select, Create a stronlgy-typed view checkbox
Select "Employee" from "Model class" dropdownlist
3. Click Add
At this point, "Index.cshtml" view should be generated. Copy and paste the following code in "Index.cshtml":
@model IEnumerable<MVCDemo.Models.Employee>
@using MVCDemo.Models;
<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.EmployeeId })</li>
}
</ul>
</div>
Description:
- @model is set to IEnumerable<MVCDemo.Models.Employee>
- Your are using Html.ActionLink html helper to generate links
And the last, please copy and paste the following code in Details.cshtml:
@Html.ActionLink("Back to List", "Index")
Congrats, you're done!
HostForLIFE.eu ASP.NET MVC 6 Hosting
HostForLIFE.eu is European Windows Hosting Provider which focuses on Windows Platform only. We deliver on-demand hosting solutions including Shared hosting, Reseller Hosting, Cloud Hosting, Dedicated Servers, and IT as a Service for companies of all sizes. We have customers from around the globe, spread across every continent. We serve the hosting needs of the business and professional, government and nonprofit, entertainment and personal use market segments.