Chapter 9B. HTML Helpers in MVC
HTML helpers are an easy way to render the appropriate HTML markup in a view and the ASP.NET MVC framework provides a wide selection of them. An HTML helper method returns an HTML-encoded string of the type MvcHtmlString
. The string can be used to render something as simple as a CheckBox
or as complicated as a complete table of data. In this lesson I show you how to use both the standard HTML helpers and the strongly-typed HTML helpers to render HTML in a web page.
Note
An MvcHtmlString
is a string that has already been HTML-encoded and therefore should not be encoded again.
STANDARD HTML HELPERS
This is the HTML used to render a TextBox
:
<input id="text1" type="text" value="My TextBox" />
This is the code, used by a view, to render the same TextBox
using an HTML helper:
<%: Html.TextBox("Text1", Model.Value) %>
In this example, the view is using the Html.TextBox
helper method. The first parameter provides the name and id for the TextBox
and the second parameter provides the value.
Note
The script delimiters <%
and %
> are used to mark the beginning and end of a script. The equal sign within the script delimiters, <%=
and %
>, is a shortcut for Response.Write
. If you forget the equal sign, the text will not be displayed because the Reponse.Write
method is not called. The colon within the script delimiters, <%:
and %
>, is also a shortcut for Response.Write
. But, in this case the string is automatically HTML-encoded.
HTML helpers are really simple to use. They are ...
Get ASP.NET 4 24-Hour Trainer now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.