zoukankan      html  css  js  c++  java
  • 使用TagBuilder类创建HTML Helpers

    Using the TagBuilder Class to Create HTML Helpers (C#)


    The ASP.NET MVC framework includes a useful utility class named the TagBuilder class that you can use when building HTML helpers. The TagBuilder class, as the name of the class suggests, enables you to easily build HTML tags. In this brief tutorial, you are provided with an overview of the TagBuilder class and you learn how to use this class when building a simple HTML helper that renders HTML <img> tags.

      ASP.NET MVC框架包含了一个很有用的实用工具类,TagBuilder类,你可以在创建HTML helpers的时候使用它。TagBuilder类,就像它的类名所暗示的那样,使你能够轻松地创建HTML标签。在这个简短的教程中,将会为你提供一个TagBuilder类的概览,你将学习如何使用这个类来创建一个简单的用于呈现HTML<img>标签的HTML Helper。

     

    Overview of the TagBuilder Class

     

    The TagBuilder class is contained in the System.Web.Mvc namespace. It has five methods:

    • AddCssClass() – Enables you to add a new class=”” attribute to a tag.
    • GenerateId() – Enables you to add an id attribute to a tag. This method automatically replaces periods in the id (by default, periods are replaced by underscores)
    • MergeAttribute() – Enables you to add attributes to a tag. There are multiple overloads of this method.
    • SetInnerText() – Enables you to set the inner text of the tag. The inner text is HTML encode automatically.
    • ToString() – Enables you to render the tag. You can specify whether you want to create a normal tag, a start tag, an end tag, or a self-closing tag.

      TagBuilder类包含在System.Web.Mvc命名空间下面,它有5个方法:

    • AddCssClass(),使您可以为标签添加一个新的 class="" 的属性。
    • GenerateId(),使您可以为标签添加一个id属性。这个方法自动替换id中句点(默认句点会被替换为下划线)。
    • MergeAttribute(),使您可以为为标签添加属性。这个方法有很多重载。
    • SetInnerText(),使您可以设置标签内的文本,标签内的文本将自动进行HTML编码。
    • ToString(),使您可以呈现一个标签,您可以指定是否要创建一个正常的标签,一个开始标签,一个结束标签,或一个自关闭标签。

    The TagBuilder class has four important properties:

    • Attributes – Represents all of the attributes of the tag.
    • IdAttributeDotReplacement – Represents the character used by the GenerateId() method to replace periods (the default is an underscore).
    • InnerHTML – Represents the inner contents of the tag. Assigning a string to this property does not HTML encode the string.
    • TagName – Represents the name of the tag.

      TabBuilder类有4个重要的属性:

    • Attributes ,代表标签的所有属性。
    • IdAttributeDotReplacement ,代表一个字符,这个字符用来在使用GenerateId()方法替换句点(默认为下划线)。
    • InnerHTML ,代表标签内的内容。将一个字符串赋值给这个属性,字符串是没有进行HTML编码的。
    • TagName ,代表标签的名称。

    These methods and properties give you all of the basic methods and properties that you need to build up an HTML tag. You don’t really need to use the TagBuilder class. You could use a StringBuilder class instead. However, the TagBuilder class makes your life a little easier.

      这些方法和属性是您想要创建HTML标签的所有基本属性和方法,您不需要一定使用TagBuilder 类,也可以使用StringBuilder类来创建HTML标签,然而TagBuilder 类将会使你更加轻松点。

    Creating an Image HTML Helper

    When you create an instance of the TagBuilder class, you pass the name of the tag that you want to build to the TagBuilder constructor. Next, you can call methods like the AddCssClass and MergeAttribute() methods to modify the attributes of the tag. Finally, you call the ToString() method to render the tag.

    For example, Listing 1 contains an Image HTML helper. The Image helper is implemented internally with a TagBuilder that represents an HTML <img> tag.

      当你要创建一个TagBuilder类的实例时,将你要创建的标签的名字传递给TagBuilder构造函数。接下来,你可以调用如AddCssClass和MergeAttribute方法来修改标签的属性,最好,调用ToString()方法来输出这个标签。

      例如,代码清单1包含了一个Image HTML helper。这个Image helper代表一个HTML<img>标签,它是由TagBuilder内部实现的。

    Listing 1 – Helpers\ImageHelper.cs

    using System.Web.Mvc;
    using System.Web.Routing;
    
    namespace MvcApplication1.Helpers
    {
        public static class ImageHelper
        {
            public static string Image(this HtmlHelper helper, string id, string url, string alternateText)
            {
                return Image(helper, id, url, alternateText, null);
            }
    
            public static string Image(this HtmlHelper helper, string id, string url, string alternateText, object htmlAttributes)
            {
                // Create tag builder
                var builder = new TagBuilder("img");
                
                // Create valid id
                builder.GenerateId(id);
    
                // Add attributes
                builder.MergeAttribute("src", url);
                builder.MergeAttribute("alt", alternateText);
                builder.MergeAttributes(new RouteValueDictionary(htmlAttributes));
    
                // Render tag
                return builder.ToString(TagRenderMode.SelfClosing);
            }
    
        }
    }
     
    
    

    The class in Listing 1 contains two static overloaded methods named Image. When you call the Image() method, you can pass an object which represents a set of HTML attributes or not.

    Notice how the TagBuilder.MergeAttribute() method is used to add individual attributes such as the src attribute to the TagBuilder. Notice, furthermore, how the TagBuilder.MergeAttributes() method is used to add a collection of attributes to the TagBuilder. The MergeAttributes() method accepts a Dictionary<string,object> parameter. The The RouteValueDictionary class is used to convert the Object representing the collection of attributes into a Dictionary<string,object>.

    After you create the Image helper, you can use the helper in your ASP.NET MVC views just like any of the other standard HTML helpers. The view in Listing 2 uses the Image helper to display the same image of an Xbox twice (see Figure 1). The Image() helper is called both with and without an HTML attribute collection.

      在代码清单1的类包含了两个静态的重载方法,Image方法。当你调用这个Image方法的时候,你可以传入一个代表一系列HTML属性的对象,你也可以不传。

      注意到TagBuilder.MergeAttribute方法是如何用来添加单个的属性,例如TagBuilder的src 属性。除此以外还需注意,MergeAttributes()方法是如何往TagBuilder添加属性集合的。MergeAttributes()方法接受一个Dictionary<string, object>参数。RouteValueDictionary类用于将代表着属性集合的对象转换为一个Dictionary<string, object>对象。

      当你创建好了Image helper之后,你可以在你的ASP.NET MVC视图中像使用其他标准的HTML helpers一样来使用这个helper。代码清单2中的视图里面使用了这个Image helper来显示两次同一Xbox图片。调用了Image的包含了HTML属性集合和不包含HTML属性集合的方法。

    Listing 2 – Home\Index.aspx

    <%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage" %>
    <%@ Import Namespace="MvcApplication1.Helpers" %>
    
    <asp:Content ID="indexContent" ContentPlaceHolderID="MainContent" runat="server">
    
        <!-- Calling helper without HTML attributes -->
        <%= Html.Image("img1", ResolveUrl("~/Content/XBox.jpg"), "XBox Console") %>
    
    
        <!-- Calling helper with HTML attributes -->
        <%= Html.Image("img1", ResolveUrl("~/Content/XBox.jpg"), "XBox Console", new {border="4px"})%>
    
    
    </asp:Content>
    
    

    Figure 01: Using the Image helper(Click to view full-size image)

  • 相关阅读:
    在dll里malloc/new/cvCreate分配内存,在exe里free/Releases释放内存时会出错。
    其原因可能是堆被损坏,这说明 100BloodCellSegTest.exe 中或它所加载的任何 DLL 中有 Bug。
    牛顿方法(Newton's Method)
    广义线性模型(Generalized Linear Models)
    逻辑回归(Logistic Regression)
    局部加权回归、欠拟合、过拟合(Locally Weighted Linear Regression、Underfitting、Overfitting)
    java并发编程实战《三》互斥锁(上)
    关于java链接装载的思考
    java并发编程实战《二》java内存模型
    (转)技术人的王者路,看看你在哪个段位?
  • 原文地址:https://www.cnblogs.com/supperwu/p/1630129.html
Copyright © 2011-2022 走看看