HTML Helpers

HTML helpers are lightweight methods that execute on the server and return a string to be used as standard HTML on your page. They are accessed using @Html, which is essentially a property on your view. The HTML helper classes and related methods are found in the namespace Microsoft.AspNet.Mvc.Rendering.

These helper methods generate UI markup and should only be used on your pages (and not in the controller). Of course, you do not need to use HTML helpers. You can code all your view as actual HTML markup. In addition, many of the HTML Helpers have evolved into TagHelpers (see next section). However, these methods can simplify writing a lot of repetitive, basic HTML markup. The methods run on the server, but they are also lightweight. (Unlike web form controls, they do not have an event model or view state.)

As an example, consider the following @Html helper inside a view page. Its job is to generate a drop-down list for user input based on a list of name-value pairs.

@Html.DropDownList(name: "Confirmed", selectList: confirmOptions)

Running this inside a view page outputs the following HTML to the browser.

<select id="Confirmed" name="Confirmed">
  <option value="1">Yes</option>
  <option value="2">No</option>
  <option value="3">Maybe</option>
</select>

Note that the preceding example requires a list of SelectListItems. You can either return them from your controller (most likely scenario) or embed the list in your page. The following shows an example of the latter just to clarify the example.

@{
  List<SelectListItem> confirmOptions = new List<SelectListItem>();

  confirmOptions.Add(new SelectListItem { Text = "Yes", Value = "1" });
  confirmOptions.Add(new SelectListItem { Text = "No", Value = "2" });
  confirmOptions.Add(new SelectListItem { Text = "Maybe", Value = "3" });
}

The HTML helper methods include one that maps to each of the form input (and related) tags covered in the earlier section, “The HTML Tags.” This includes the following helper methods: @Html.CheckBox, @Html.DropDownList, @Html.Hidden, @Html.Label, @Html.ListBox, @Html.Password, @Html.RadioButton, and @Html.TextArea. Each of these helper methods also defines a similar method that includes the word For appended to the end, as in @Html.TextBoxFor. You use the “For” HTML helper methods for model binding—that is, when you want to have ASP.NET output-specific HTML for a given property in your model. The following shows an example.

@Html.EditorFor(model => model.Email,
  new { htmlAttributes = new { @class = "form-control" } })

Notice that this example uses model binding inside a strongly typed view (more on this in a moment). Notice, too, that you can use one of the additional overloads of the helper method to set specific HTML attributes on the HTML to be output (in this case, the style class name).

There are many additional HTML helpers designed to take advantage of the server-side ASP.NET engine and make writing HTML easier. The following provides a list of some of these key helper methods you are likely to encounter:

Image @Html.BeginForm—Used to create a <form> tag inside your view.

Image @Html.AntiForgeryToken—Used to generate an anti-forgery key to be validated back on the controller (provided you decorate your controller method with the ValidateAntiForgeryToken attribute). See the example later in this section.

Image @Html.ValidationSummary—Used to create an error on your page to display a summary of field validation errors on the page.

Image @Html.LabelFor—Used to generate a label for one of your input items.

Image @Html.EditorFor—Used to create an editor (typically an <input> tag) for a given property of your model. This allows the framework to select the editor on your behalf (based on data type).

Image @Html.ValidationMessageFor—Used to create messages that display when a field has an error (and hide when it does not).

Image @Html.ActionLink—Used to create a hyperlink on your page that can also call your controller (including using HTTP POST).

Image @Html.Encode—Used to convert a value to an HTML-encoded string for output.

You will use these helper methods throughout the remainder of this section to write sample view pages for the customer example discussed earlier.


Create Custom Html Helpers

You can build your own Razor HTML helpers. You create these helpers to make writing markup easier for you or your team of developers. A custom helper can contain both code and markup. It will show up in IntelliSense and work the same way as other HTML helpers to generate markup for you.


ASP.NET MVC TagHelpers

ASP.NET MVC 6 introduces TagHelpers to provide a more markup-based approach to extending HTML with server-side code processing. Like HTML Helpers, TagHelpers process on the server and simplify the writing of repetitive code. What makes them different is that they look and feel more like HTML markup. There is no need for the @Html signal in your markup to indicate a server-side helper method is being called. Instead, the TagHelpers add custom attributes to existing HTML tags. This makes them look and feel like HTML markup (but can be color coded for easy identification in the IDE). These attributes then execute on the server much the same way a HTML helper would. The TagHelper classes are found in the namespace Microsoft.AspNet.Mvc.TagHelpers.

Let’s look at an example. The following is a call inside markup to an HTML Helper for creating a hyperlink that works with the CustomerController (based on convention of the URL) and the Edit action method. This looks and acts like code inside of markup.

@Html.ActionLink("Edit", "Edit", new { id= item.Id })

The same link can be written as follows using a TagHelper:

<a asp-controller="Customer" asp-action="Edit"
  asp-route-id="@item.Id">Customer</a>

Notice this is just HTML markup with two custom attributes: asp-controller and asp-action. This can be easier to write and to read for developers used to writing and working with markup. This also includes the optional, asp-route-id to append an id parameter to the controller request. There are additional attributes as well, such as asp-fragment, for pointing to a section of the page being linked.

There are many such TagHelpers available in the new ASP.NET MVC 6. They can be identified easily in markup by their default attribute color, purple. The following outlines the TagHelpers available. We will use TagHelpers throughout the rest of this chapter and in some upcoming chapters.

Image Anchor—Used to create hyperlinks using the <a/> tag as shown above.

Image Cache—A special tag that supports partial page caching.

Image Environment—A special tag that allows you to control the page rendering based on runtime environments such as development, staging, and production.

Image Form—Augments the <form/> tag for creating forms bound to MVC models.

Image Input—Extends the <input/> tag for creating input elements based on strongly typed model data.

Image Label—Used on the <label/> tag to create labels for model elements.

Image Link—Used to process link elements.

Image Option—Used to work with individual options in a select list.

Image Script—Simplifies writing script tags.

Image Select—Extends the <select/> tag to generate dropdown lists.

Image TextArea—Augments the <textarea/> tag for model elements.

Image ValidationMessage—Used to display validation messages inside a <span/> for individual model elements.

Image ValidationSummary—Used to show a validation summary of validation issues for a given model.


Create Custom Tag Helpers

You can write your own TagHelpers for ASP.NET to generate code based on markup. This is very similar to creating HTML Helpers. You will also see TagHelpers available from various control vendors.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset