MVC HTML helper
ASP.NET MVC - HTML Helper
HTML helper is used to modify HTML output.
HTML Helpers
With MVC, HTML helpers are similar to traditional ASP.NET Web Form controls.
Like the Web Form control in ASP.NET, HTML helpers are used to modify HTML. But HTML helpers are more lightweight. Unlike Web Form controls, HTML helpers have no event model and no view state.
In most cases, an HTML helper is just 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 HTML links is to use the HTML.ActionLink() helper.
With MVC, Html.ActionLink() does not connect to the view. It creates a connection to the controller action.
Razor syntax:
ASP syntax:
The first parameter is the link text, and the second parameter is the controller operation The name.
The above Html.ActionLink() helper outputs the following HTML:
Some properties of Html.ActionLink() helper:
Properties | Description |
---|---|
.linkText | URL text (label), the internal text of the anchor element. |
.actionName | The name of the action. |
.routeValues | The value passed to the action is an object containing routing parameters. |
.controllerName | The name of the controller. |
.htmlAttributes | Attribute setting for URL is an object containing the HTML attributes to be set for this element. |
.protocol | URL protocol, such as "http" or "https". |
.hostname | The hostname of the URL. |
.fragment | URL fragment name (anchor name). |
Notes: You can pass values to controller actions. For example, you can pass the id of the database record to the database Edit action:
Razor Syntax C#:
Razor syntax VB:
The above Html.ActionLink() helper outputs the following HTML:
HTML form elements
The following HTML helpers can be used to render (modify and output) HTML form elements:
- BeginForm ()
- EndForm()
- TextArea()
- TextBox()
- CheckBox()
- RadioButton()
- ListBox()
- DropDownList()
- Hidden()
- Password()
ASP.NET Syntax C#:
<% using (Html.BeginForm()){%>
<p>
<label for="FirstName">First Name:</label>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>
</p>
<p>
<label for="LastName">Last Name:</label>
<%= Html.TextBox("LastName") %>
<%= Html.ValidationMessage("LastName", "*") %>
</p>
<p>
<label for="Password">Password:</label>
<%= Html.Password("Password") %>
<%= Html.ValidationMessage("Password", "*") %>
</p>
<p>
<label for="Password">Confirm Password:</label>
<%= Html.Password("ConfirmPassword") %>
<%= Html.ValidationMessage("ConfirmPassword", "*") %>
</p>
<p>
<label for="Profile">Profile:</label>
<%= Html.TextArea("Profile", new {cols=60, rows=10})%>
</p>
<p>
<%= Html.CheckBox("ReceiveNewsletter") %>
<label for="ReceiveNewsletter" style="display:inline">Receive Newsletter?</label>
</p>
<p>
<input type="submit" value="Register" />
</p>
<%}%>