Create custom HTML helper

Source: Internet
Author: User
Document directory
  • Understand HTML helper
  • Use static methods to Create HTML helper
  • Create HTML helper using extension methods
  • Summary

This tutorial shows you how to create a custom HTML helper in your MVC view. HTML helpers can be used to reduce tedious HTML tags.

In the first part of the tutorial, I described the existing HTML helper of ASP. NET MVC framework. Then, I described two methods for creating custom HTML helper: I will explain how to create HTML helper by creating static and extension methods.

Understand HTML helper

HTML helper is just a method for returning strings. This string can represent any content you want. For example, you can use HTML helper to present standard HTML tags such as HTML<input>AndLabel. You can also use HTML helper to present more complex content, such as an HTML table of a tab or database data.

The ASP. net mvc framework includes the following standard HTML helpers (this list is not complete ):

  • Html. actionlink ()
  • Html. beginform ()
  • Html. checkbox ()
  • Html. dropdownlist ()
  • Html. endform ()
  • Html. Hidden ()
  • Html. ListBox ()
  • Html. Password ()
  • Html. radiobutton ()
  • Html. textarea ()
  • Html. Textbox ()

For example, consider the form of Code 1. This form is rendered by two standard HTML helper (see figure 1 ). This form usesHtml.BeginForm()AndHtml.TextBox()Helper method to render a simple HTML form.

Figure 01: Page rendered by HTML helper (click to view the full size)

Code 1-Views/Home/Index.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Views.Home.Index"%><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><ptml xmlns= "http://www.w3.org/1999/xhtml "><pead id="Head1" runat="server">     <title>Index</title></pead><body>      <div>          <% using (Html.BeginForm())          { %>               <label for="firstName">First Name:</label>               <br />               <%= Html.TextBox("firstName")%>               <br /><br />               <label for="lastName">Last Name:</label>               <br />               <%= Html.TextBox("lastName")%>               <br /><br />               <input type="submit" value="Register" />              <% } %>     1     </div></body></ptml>

Html. beginform () helper method is used to create html<form>The start and end of a tag. Note:Html.BeginForm()Method is called in a using statement. Using statement to ensure<form>The label can be disabled at the end of the using block.

If you want to disable the using block, you can call the HTML. endform () helper method to disable it.<form>Label. If you think it is intuitive, you can use it.

Html.TextBox()The Helper method is used to render HTML<input>Label. If you select to view the source code in the browser, you will see the HTML source shown in 2. Note that the source code contains standard HTML tags.

Important: NoteHtml.TextBox()-HTML helper<%= %>Label instead<% %>Label. If you do not add this equal sign, the browser will not render anything.

The ASP. net mvc Framework contains a group of helpers. In October, you will need to use custom HTML helper to extend the MVC framework. In the rest of this tutorial, you will learn two ways to create a custom HTML helper.

Code 2-Index.aspx Source

<%@ Page Language="C#" AutoEventWireup="false" CodeBehind="Index.aspx.cs" Inherits="MvcApplication1.Index" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><ptml xmlns="http://www.w3.org/1999/xhtml"><pead>     <title>Index</title></pead><body>     <div>          <form action="http://localhost:33102/" method="post">               <label for="firstName">First Name:</label>               <br />               <input id="firstName" name="firstName" type="text" value="" />               <br /><br />               <label for="lastName">Last Name:</label>               <br />               <input id="lastName" name="lastName" type="text" value="" />               <br /><br />               <input id="btnRegister" name="btnRegister" type="submit" value="Register" />          </form>     </div></body></ptml>
Use static methods to Create HTML helper

The simplest way to Create HTML helper is to create a static method that returns a string. For example, you decide to create an HTML helper to render the html<label>Label. You can use the class in code 3 to present<label>.

Code 3-Helpers/LabelHelper.cs

using System;namespace MvcApplication1.Helpers{          public class LabelHelper          {               public static string Label(string target, string text)               {                    return String.Format("<label for='{0}'>{1}</label>", target, text);               }          }}

The class in code 3 is nothing special.Label()Method returns only one string.

Use the modified index view in code 4LabelHelperRendering html<label>Label. Note that the view includes<%@ imports %>Command to introduceApplication1.HelpersNamespace.

Code 4-Views/Home/Index2.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index2.aspx.cs" Inherits="MvcApplication1.Views.Home.Index2"%><%@ Import Namespace="MvcApplication1.Helpers" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><ptml xmlns="http://www.w3.org/1999/xhtml" ><pead id="Head1" runat="server">     <title>Index2</title></pead><body>     <div>          <% using (Html.BeginForm())          { %>               <%= LabelHelper.Label("firstName", "First Name:") %>               <br />               <%= Html.TextBox("firstName")%>               <br /><br />               <%= LabelHelper.Label("lastName", "Last Name:") %>               <br />               <%= Html.TextBox("lastName")%>               <br /><br />               <input type="submit" value="Register" />          <% } %>     </div></body></ptml>
Create HTML helper using extension methods

If you want to create HTML helper as standard HTML helper in the ASP. net mvc framework, you need to create extension methods. The extension method allows you to add new methods in the existing class. When creating an HTML helper method, add a new method for the htmlhelper class, which is represented by the HTML attribute of the view.

The class in code 5 adds an extension method named label ()HtmlHelper。You need to pay attention to this class. First, note that this class is a static class. You must define extension methods to static classes.

Second, note thatLabel()A keyword exists before the first parameter of the method.this. The first parameter of the extension method indicates the class extended by the extension method.

Code 5-Helpers/LabelExtensions.cs

using System;using System.Web.Mvc;namespace MvcApplication1.Helpers{     public static class LabelExtensions     {          public static string Label(this HtmlHelper helper, string target, string text)          {               return String.Format("<label for='{0}'>{1}</label>", target, text);          }     }}

After an extension method is created and your application is successfully generated, the extension method can be displayed in the Visual Studio smart tip just like all the methods in other classes. (See figure 2 ). The only difference is that the icon next to the extension method is special (a down arrow ).

Figure 02: Use HTML. Label () Extension Method (click to view the full size)

The modified index view in code 6 presents all its<label>Label.

Code 6-Views/Home/Index3.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Index3.aspx.cs" Inherits="MvcApplication1.Views.Home.Index3" %><%@ Import Namespace="MvcApplication1.Helpers" %><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><ptml xmlns="http://www.w3.org/1999/xhtml" ><pead id="Head1" runat="server">     <title>Index3</title></pead><body>     <div>          <% using (Html.BeginForm())          { %>               <%= Html.Label("firstName", "First Name:") %>                   <br />               <%= Html.TextBox("firstName")%>               <br /><br />               <%= Html.Label("lastName", "Last Name:") %>                   <br />               <%= Html.TextBox("lastName")%>               <br /><br />               <input type="submit" value="Register" />          <% } %>     </div></body></ptml>
Summary

In this tutorial, you learned two methods to create a custom HTML helper. First, you learned how to create a custom string by creating a static method that returns the string.Label()HTML helper. Then, you learned how to create a custom by creating an extension method class in the htmlhelper class.Label()HTML helper.

In this tutorial, I focus on creating an extremely simple HTML helper method. Note that HTML helper can be completed as you want. You can create HTML helper that presents rich content such as tree lists, menus, or tables recorded in the database.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.