创建自定义 HTML 帮助程序 (C#)Creating Custom HTML Helpers (C#)

by Microsoftby Microsoft

下载 PDFDownload PDF

本教程的目的是演示如何创建自定义 HTML 帮助程序,你可以使用您的 MVC 视图中。The goal of this tutorial is to demonstrate how you can create custom HTML Helpers that you can use within your MVC views. 通过利用 HTML 帮助程序,可以减少量,你必须执行来创建标准的 HTML 页面的 HTML 标记的类型设置枯燥乏味。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.

本教程的目的是演示如何创建自定义 HTML 帮助程序,你可以使用您的 MVC 视图中。The goal of this tutorial is to demonstrate how you can create custom HTML Helpers that you can use within your MVC views. 通过利用 HTML 帮助程序,可以减少量,你必须执行来创建标准的 HTML 页面的 HTML 标记的类型设置枯燥乏味。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.

在本教程的第一个部分中,我介绍了一些现有 ASP.NET MVC framework 附带的 HTML 帮助程序。In the first part of this tutorial, I describe some of the existing HTML Helpers included with the ASP.NET MVC framework. 接下来,我将介绍创建自定义 HTML 帮助程序的两个方法:我将介绍如何创建自定义 HTML 帮助程序,通过创建一个静态方法,并创建扩展方法。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.

了解 HTML 帮助程序Understanding HTML Helpers

HTML 帮助器就是返回一个字符串的方法。An HTML Helper is just a method that returns a string. 该字符串可表示任何类型的所需的内容。The string can represent any type of content that you want. 例如,使用 HTML 帮助器来呈现标准 HTML 标记与 HTML 一样<input><img>标记。For example, you can use HTML Helpers to render standard HTML tags like HTML <input> and <img> tags. 此外可以使用 HTML 帮助器来呈现选项卡条带或 HTML 表的数据库数据等更复杂的内容。You also can use HTML Helpers to render more complex content such as a tab strip or an HTML table of database data.

ASP.NET MVC 框架包括以下一组标准的 HTML 帮助程序 (这不是完整的列表):The ASP.NET MVC framework includes the following set of standard HTML Helpers (this is not a complete list):

  • Html.ActionLink()Html.ActionLink()
  • Html.BeginForm()Html.BeginForm()
  • Html.CheckBox()Html.CheckBox()
  • Html.DropDownList()Html.DropDownList()
  • Html.EndForm()Html.EndForm()
  • Html.Hidden()Html.Hidden()
  • Html.ListBox()Html.ListBox()
  • Html.Password()Html.Password()
  • Html.RadioButton()Html.RadioButton()
  • Html.TextArea()Html.TextArea()
  • Html.TextBox()Html.TextBox()

例如,考虑列表 1 中的窗体。For example, consider the form in Listing 1. 呈现此窗体所使用的两个标准 HTML 帮助程序 (请参阅图 1) 的帮助。This form is rendered with the help of two of the standard HTML Helpers (see Figure 1). 使用此窗体Html.BeginForm()Html.TextBox()帮助器方法来呈现一个简单的 HTML 窗体。This form uses the Html.BeginForm() and Html.TextBox() Helper methods to render a simple HTML form.

与 HTML 帮助器呈现页Page rendered with HTML Helpers

图 01:与 HTML 帮助器呈现的页 (单击此项可查看原尺寸图像)Figure 01: Page rendered with HTML Helpers (Click to view full-size image)

代码清单 1 – Views\Home\Index.aspxListing 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>

Html.BeginForm() 帮助器方法用于创建开始和结束 HTML<form>标记。The Html.BeginForm() Helper method is used to create the opening and closing HTML <form> tags. 请注意,Html.BeginForm()方法调用中的 using 语句。Notice that the Html.BeginForm() method is called within a using statement. 使用语句将确保<form>标记获取使用的结尾处结束块。The using statement ensures that the <form> tag gets closed at the end of the using block.

如果您愿意,而不是创建一个 using 块中,您可以调用 Html.EndForm() 帮助器方法来关闭<form>标记。If you prefer, instead of creating a using block, you can call the Html.EndForm() Helper method to close the <form> tag. 使用任何方法来创建一个打开和关闭<form>似乎是最直观的标记。Use whichever approach to creating an opening and closing <form> tag that seems most intuitive to you.

Html.TextBox()帮助器方法用于在列表 1 中呈现 HTML<input>标记。The Html.TextBox() Helper methods are used in Listing 1 to render HTML <input> tags. 如果你看到代码清单 2 中的 HTML 源,然后在浏览器中选择查看源。If you select view source in your browser then you see the HTML source in Listing 2. 请注意源包含标准的 HTML 标记。Notice that the source contains standard HTML tags.

Important

请注意,Html.TextBox()帮助器呈现 HTML<%= %>标记而不是<% %>标记。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.

ASP.NET MVC 框架包含一小组帮助程序。The ASP.NET MVC framework contains a small set of helpers. 很可能需要扩展 MVC 框架使用自定义 HTML 帮助程序。Most likely, you will need to extend the MVC framework with custom HTML Helpers. 在本教程的其余部分,了解创建自定义 HTML 帮助程序的两个方法。In the remainder of this tutorial, you learn two methods of creating custom HTML Helpers.

代码清单 2 – Index.aspx SourceListing 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>

创建包含静态方法的 HTML 帮助程序Creating HTML Helpers with Static Methods

若要创建新的 HTML 帮助器的最简单方法是创建返回的字符串的静态方法。The easiest way to create a new HTML Helper is to create a static method that returns a string. 例如,假设你决定创建新的 HTML 帮助程序呈现 HTML<label>标记。Imagine, for example, that you decide to create a new HTML Helper that renders an HTML <label> tag. 可以使用在代码清单 2 中的类来呈现<label>You can use the class in Listing 2 to render a <label> .

代码清单 2 – Helpers\LabelHelper.csListing 2 – 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);
        }
    }
}

没有什么特别之处代码清单 2 中的类。There is nothing special about the class in Listing 2. Label()方法只返回一个字符串。The Label() method simply returns a string.

列表 3 中已修改的索引视图使用LabelHelper呈现 HTML<label>标记。The modified Index view in Listing 3 uses the LabelHelper to render HTML <label> tags. 请注意,该视图包含<%@ imports %>导入指令Application1.Helpers命名空间。Notice that the view includes an <%@ imports %> directive that imports the Application1.Helpers namespace.

代码清单 2 – Views\Home\Index2.aspxListing 2 – 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>

使用扩展方法创建 HTML 帮助程序Creating HTML Helpers with Extension Methods

如果你想要创建的 HTML 帮助程序就类似于标准的 HTML 帮助程序,它们包含在 ASP.NET MVC framework,则需要创建扩展方法。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. 时创建的 HTML 帮助器方法,您将新方法添加到视图的 Html 属性表示 HtmlHelper 类。When creating an HTML Helper method, you add new methods to the HtmlHelper class represented by a view's Html property.

列表 3 中的类添加到扩展方法HtmlHelper类名为Label()The class in Listing 3 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.

其次,注意的第一个参数Label()方法前面由关键字thisSecond, 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.

代码清单 3 – Helpers\LabelExtensions.csListing 3 – 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);
          }
     }
}

创建一个扩展方法,并已成功生成应用程序后,扩展方法将出现在 Visual Studio Intellisense 等所有其他方法的类 (请参见图 2)。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).

使用 Html.Label() 扩展方法Using the Html.Label() extension method

图 02:使用 Html.Label() 扩展方法 (单击此项可查看原尺寸图像)Figure 02: Using the Html.Label() extension method (Click to view full-size image)

列表 4 中经过修改的索引视图使用 Html.Label() 扩展方法呈现的所有其<label>标记。The modified Index view in Listing 4 uses the Html.Label() extension method to render all of its <label> tags.

列表 4 – Views\Home\Index3.aspxListing 4 – 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

在本教程中,您学习了创建自定义 HTML 帮助程序的两个方法。In this tutorial, you learned two methods of creating custom HTML Helpers. 首先,您学习了如何创建自定义Label()通过创建一个静态方法的 HTML 帮助器返回的字符串。First, you learned how to create a custom Label() HTML Helper by creating a static method that returns a string. 接下来,您学习了如何创建自定义Label()上创建扩展方法的 HTML 帮助器方法HtmlHelper类。Next, you learned how to create a custom Label() HTML Helper method by creating an extension method on the HtmlHelper class.

在本教程中,我专注于构建一个非常简单的 HTML 帮助器方法。In this tutorial, I focused on building an extremely simple HTML Helper method. 请注意,HTML 帮助器可以是你想的那么复杂。Realize that an HTML Helper can be as complicated as you want. 您可以构建丰富的内容,如树视图、 菜单或表的数据库数据呈现的 HTML 帮助程序。You can build HTML Helpers that render rich content such as tree views, menus, or tables of database data.