创建自定义的HTML Helper

Creating Custom HTML Helpers

The goal of this tutorial is to demonstrate how you can create custom HTML Helpers that you can use within your MVC views. By taking advantage of HTML Helpers, you can reduce the amount of tedious typing of HTML tags that you must perform to create a standard HTML page.

In the first part of this tutorial, I describe some of the existing HTML Helpers included with the ASP.NET MVC framework. Next, I describe two methods of creating custom HTML Helpers: I explain how to create custom HTML Helpers by creating a static method and by creating an extension method.

 

  这篇教程的目的是演示如何创建在MVC视图中使用的自定义HTML Helper。通过利用HTML Helpers,你可以减少大量HTML标签的输入,你必须输入这些标签来创建标准的HTML页面。

  在这篇教程的第一部分,我描述了一些在ASP.NET MVC中中已经存在的HTML Helper。接下来,我描述了两种创建自定义HTML Helpers的方法:我将演示如何通过创建静态方法和创建扩展方法来创建自定义HTML Helpers。

 

Understanding HTML Helpers

An HTML Helper is just a method that returns a string. The string can represent any type of content that you want. For example, you can use HTML Helpers to render standard HTML tags like HTML <input> and <img> tags. You also can use HTML Helpers to render more complex content such as a tab strip or an HTML table of database data.

The ASP.NET MVC framework includes the following set of standard HTML Helpers (this is not a complete list):

  • 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 in Listing 1. This form is rendered with the help of two of the standard HTML Helpers (see Figure 1). This form uses the Html.BeginForm() and Html.TextBox() Helper methods to render a simple HTML form.

 

  HTML Helper只不过是一个返回字符串的方法。这个字符串可以表示任何你想要类型的内容。例如,你可以使用HTML Helper来呈现标准的HTML标签,类似HTML <input>和<img>标签。你也可以使用HTML Helpers来呈现更加复杂的内容,例如一个标签页或者一个数据库数据的HTML表格。

ASP.NET MVC框架包含了一系列以下标准的HTML Helpers(这里不是全部的):省略……

 

例如,考虑代码清单1中的表单。这个表单是在两个标准的HTML Helpers的帮助下呈现的。这个表单使用了Html.BeginForm()和Html.TextBox()Helper方法来呈现一个简单的HTML表单。

 

 

Figure 01: Page rendered with HTML Helpers (Click to view full-size image)

Listing 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">
<html xmlns= "http://www.w3.org/1999/xhtml ">
<head id="Head1" runat="server">
     <title>Index</title>
</head>
<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>
</html>
    

The Html.BeginForm() Helper method is used to create the opening and closing HTML <form> tags. Notice that the Html.BeginForm() method is called within a using statement. The using statement ensures that the <form> tag gets closed at the end of the using block.

If you prefer, instead of creating a using block, you can call the Html.EndForm() Helper method to close the <form> tag. Use whichever approach to creating an opening and closing <form> tag that seems most intuitive to you.

The Html.TextBox() Helper methods are used in Listing 1 to render HTML <input> tags. If you select view source in your browser then you see the HTML source in Listing 2. Notice that the source contains standard HTML tags.

IMPORTANT: notice that the Html.TextBox()-HTML Helper is rendered with <%= %> tags instead of <% %> tags. If you don't include the equal sign, then nothing gets rendered to the browser.

The ASP.NET MVC framework contains a small set of helpers. Most likely, you will need to extend the MVC framework with custom HTML Helpers. In the remainder of this tutorial, you learn two methods of creating custom HTML Helpers.

 

  Html.BeginForm()Helper方法用于创建HTML<form>的开闭标签。注意到Html.BeginForm()方法在一个using语句内被调用。using语句确保了<form>标记在using块末尾关闭。

  如果你喜欢,你可以调用Html.EndForm()Helper方法来关闭<form>标签代替创建using语句块。使用你认为最直观的方法来创建<form>的开闭标签。

  Html.TextBox()Helper方法在代码清单1中用于呈现HTML<input>标签。如果你在你的浏览器中选择“查看源文件”,那么你会看到代码清单2中的HTML源代码。注意到源代码中包含了标准的HTML标签。

重点:注意Html.TextBox(),HTML Helper使用<%= %>标签来呈现,而不是<% %>标签。如果你不包含这个等号,那么不会有任何东西呈现至浏览器。

  ASP.NET MVC框架包含很少一些Helpers方法。大多数情况,你需要使用自定义HTML Helpers来扩展MVC框架。在这篇教程的剩余部分,你会学习两个创建自定义HTML Helpers的方法。

 

 

Listing 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">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
     <title>Index</title>
</head>
<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>
</html>
        

Creating HTML Helpers with Static Methods

The easiest way to create a new HTML Helper is to create a static method that returns a string. Imagine, for example, that you decide to create a new HTML Helper that renders an HTML <label> tag. You can use the class in Listing 2 to render a<label> .

 

  创建一个新HTML Helper的最简单方法就是创建一个返回字符串的静态方法。例如,假设你决定创建一个HTML Helper,它呈现一个HTML <label>标签。你可以使用代码清单3中的类来呈现一个<label>。

 

Listing 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);
               }
          }
}
        

There is nothing special about the class in Listing 2. The Label() method simply returns a string.

The modified Index view in Listing 3 uses the LabelHelper to render HTML <label> tags. Notice that the view includes an<%@ imports %> directive that imports the Application1.Helpers namespace.

 

 

  对于代码清单2中的类没什么特别要说的。Label()方法简单地返回了一个字符串。

  代码清单4中修改过了的Index视图使用了LabelHelper来呈现HTML <label>标签。注意到视图包含一个<%@ imports %>指令,它导入了Application1.Helpers命名空间。

 

 

Listing 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">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
     <title>Index2</title>
</head>
<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>
</html>
        

Creating HTML Helpers with Extension Methods

If you want to create HTML Helpers that work just like the standard HTML Helpers included in the ASP.NET MVC framework then you need to create extension methods. Extension methods enable you to add new methods to an existing class. When creating an HTML Helper method, you add new methods to the HtmlHelper class represented by a view's Html property.

The class in Listing 5 adds an extension method to the HtmlHelper class named Label(). There are a couple of things that you should notice about this class. First, notice that the class is a static class. You must define an extension method with a static class.

Second, notice that the first parameter of the Label() method is preceded by the keyword this. The first parameter of an extension method indicates the class that the extension method extends.

 

 

  如果你想创建一个HTML Helpers,就好像它包含在ASP.NET MVC框架中标准的HTML Helpers,那么你需要创建扩展方法。扩展方法使你能够为已有的类添加新的方法。当创建HTML Helper方法的时候,你为HtmlHelper类添加新的方法,该类由视图的Html属性所表示。

  代码清单5中的类为HtmlHelper类添加了一个叫做Label()的扩展方法。这里有几个你需要注意的地方。首先,注意到这个类是一个静态类。你必须将扩展方法定义在静态类中。

其次,注意到Label()方法的第一个参数前面有一个关键字this。扩展方法的第一个参数说明了这个扩展方法所扩展的类。

 

 

Listing 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 you create an extension method, and build your application successfully, the extension method appears in Visual Studio Intellisense like all of the other methods of a class (see Figure 2). The only difference is that extension methods appear with a special symbol next to them (an icon of a downward arrow).

 

  创建了扩展方法后,并且成功生成了应用程序之后,扩展方法会出现在Visual Stuidio的智能感知中,就好像这个类的所有其他方法一样(如图2)。唯一的区别是扩展方法出现时在它们旁边有一个特殊的标记(一个向下的箭头图标)。

 

Figure 02: Using the Html.Label() extension method (Click to view full-size image)

The modified Index view in Listing 6 uses the Html.Label() extension method to render all of its <label> tags.

  代码清单6中修改后的Index视图使用了Html.Label()扩展方法来呈现它所有的<label>标签。

 

Listing 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">
<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1" runat="server">
     <title>Index3</title>
</head>
<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>
</html>
        

Summary

In this tutorial, you learned two methods of creating custom HTML Helpers. First, you learned how to create a custom Label() HTML Helper by creating a static method that returns a string. Next, you learned how to create a custom Label() HTML Helper method by creating an extension method on the HtmlHelper class.

In this tutorial, I focused on building an extremely simple HTML Helper method. Realize that an HTML Helper can be as complicated as you want. You can build HTML Helpers that render rich content such as tree views, menus, or tables of database data.

 

  在这篇教程中,你学习了两种创建自定义HTML Helpers的方法。首先,你学习了如何通过创建返回字符串的静态方法来创建自定义Label() HTML Helper。接下来,你学习了如何通过在HtmlHelper类上创建扩展方法来创建自定义Label()Html Helper方法。

  在这篇教程中,我将精力集中在创建极其简单的HTML Helper方法。应该意识到你想要多么复杂,HTML Helper就可以多么复杂。你可以创建HTML Helpers来呈现丰富的内容,例如树形结构、菜单或者数据库数据表格。

 

 

posted @ 2009-12-15 00:15  supperwu  阅读(757)  评论(0编辑  收藏  举报