ASP.NET Core 5.0 MVC HTML Helpers Edit

Murugan Andezuthu Dharmaratnam | 18 January 2021 | 151

Introduction

HTML Helpers are methods that return a string. Helper class can create HTML controls programmatically. HTML Helpers are used in View to render HTML content. It is not mandatory to use HTML Helper classes for building an ASP.NET MVC application. We can build an ASP.NET MVC application without using them, but HTML Helpers helps in the rapid development of a view. HTML Helpers are more lightweight as compared to ASP.NET Web Form controls as they do not use ViewState and do not have event models. We can create custom HTML helpers.

@Html is an object of the HtmlHelper class. @ symbol is used to access server-side object in razor syntax. The ActionLink() and DisplayNameFor() are extension methods included in the HtmlHelper class. The HtmlHelper class generates HTML elements. For example, @Html.ActionLink("Create New", "Create") would generate anchor tag Create New

Example

@model IEnumerable @{ ViewData["Title"] = "Index"; }

Index

Create New

@foreach (var item in Model) { }
@Html.DisplayNameFor(model => model.Id) @Html.DisplayNameFor(model => model.Name) @Html.DisplayNameFor(model => model.Code)
@Html.DisplayFor(modelItem => item.Id) @Html.DisplayFor(modelItem => item.Name) @Html.DisplayFor(modelItem => item.Code) @Html.ActionLink("Edit", "Edit", new { id=item.Id }) | @Html.ActionLink("Details", "Details", new { id = item.Id }) | @Html.ActionLink("Delete", "Delete", new { id=item.Id })

Output