Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

ASP.NET MVC HTML Helpers

ASP.NET MVC - HTML Helpers


HTML helpers are used to modify HTML output.


HTML helper

With MVC, HTML helpers are similar to traditional ASP.NET Web Form controls.

Like Web Form controls in ASP.NET, HTML helpers are used to modify HTML. But HTML helpers are lighter-weight. Unlike Web Form controls, HTML helpers have no event model or view state.

In most cases, an HTML helper is simply a method that returns a string.

With MVC, you can create your own helpers, or use the built-in HTML helpers directly.


Standard HTML helpers

MVC includes standard helpers for most commonly used HTML element types, such as HTML links and HTML form elements.


HTML links

The simplest way to render an HTML link is to use the HTML.ActionLink() helper.

With MVC, Html.ActionLink() does not link to a view. It creates a link to a controller action.

Razor syntax:

@Html.ActionLink("About this Website", "About")

ASP syntax:

<%=Html.ActionLink("About this Website", "About")%>

The first parameter is the link text, and the second parameter is the name of the controller action.

The Html.ActionLink() helper above outputs the following HTML:

About this Website

Some properties of the Html.ActionLink() helper:

property Description
.linkText The URL text (label), the inner text of the anchor element.
.actionName The name of the action.
.routeValues The value passed to the action, an object containing route parameters.
.controllerName The name of the controller.
.htmlAttributes The URL attribute settings, an object containing the HTML attributes to set for the element.
.protocol The URL protocol, such as "http" or "https".
.hostname The host name of the URL.
.fragment The URL fragment name (anchor name).

**Note:** You can pass values to controller actions. For example, you can pass the id of a database record to the database Edit action:

Razor syntax C#:

@Html.ActionLink("Edit Record", "Edit", new {Id=3})

Razor syntax VB:

@Html.ActionLink("Edit Record", "Edit", New With{.Id=3})

The Html.ActionLink() helper above outputs the following HTML:

Edit Record


HTML form elements

The following HTML helpers can be used to render (modify and output) HTML form elements:

ASP.NET syntax C#:

<%= Html.ValidationSummary("Create was unsuccessful. Please correct the errors and try again.") %>

<% using (Html.BeginForm()){%>

<%= Html.TextBox("FirstName") %>

<%= Html.ValidationMessage("FirstName", "*") %>

<%= Html.TextBox("LastName") %>

<%= Html.ValidationMessage("LastName", "*") %>

<%= Html.Password("Password") %>

<%= Html.ValidationMessage("Password", "*") %>

<%= Html.Password("ConfirmPassword") %>

<%= Html.ValidationMessage("ConfirmPassword", "*") %>

<%= Html.TextArea("Profile", new {cols=60, rows=10})%>

<%= Html.CheckBox("ReceiveNewsletter") %>

<%}%>