HI WELCOME TO SIRIS

Part 33 - Html helpers in mvc

Leave a Comment
we will discuss
1. The purpose of html helpers
2. Some of the standard html helpers



What is an HTML helper?
An HTML helper is a method that is used to render html content in a view. HTML helpers are implemented as extension methods.

For example, to produce the HTML for a textbox with id="firstname" and name="firstname", we can type all the html in the view as shown below
<input type="text" name="firtsname" id="firstname" />

OR

We can use the "TextBox" html helper. 
@Html.TextBox("firstname")



There are several overloaded versions. To set a value, along with the name, use the following overloaded version.
@Html.TextBox("firstname", "John")

The above html helper, generates the following HTML
<input id="firstname" name="firstname" type="text" value="John" />

To set HTML attributes, use the following overloaded version. Notice that, we are passing HTML attributes (style title) as an anonymous type.
@Html.TextBox("firstname", "John", new { style = "background-color:Red; color:White; font-weight:bold", title="Please enter your first name" })
Some of the html attributes, are reserved keywords. Examples include class, readonly etc. To use these attributes, use "@" symbol as shown below.
@Html.TextBox("firstname""John"new { @class = "redtextbox", @readonly="true" })

To generate a label for "First Name"
@Html.Label("fisrtname""First Name")

To generate a textbox to enter password, so that the input is masked
@Html.Password("Password")

To generate a multi-line textbox with 5 rows and 20 columns
@Html.TextArea("Comments""", 5, 20, null)

To generate a hidden textbox
@Html.Hidden("id")

Hidden textbox is used to store id values. Id values are not displayed on the page to the end user, but we need them to update data when the form is posted to the server.

Is it possible to create our own custom html helpers?
Yes, we will discuss this in a later video session.

Is it mandatory to use HTML helpers?
No, you can type the required HTML, but using HTML helpers will greatly reduce the amount of HTML that we have to write in a view. Views should be as simple as possible. All the complicated logic to generate a control can be encapsulated into the helper, to keep views simple.

0 comments:

Post a Comment

Note: only a member of this blog may post a comment.