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.

  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.

  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.

  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.

  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.

  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.

  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>

  Notice that you must import the namespace  associated with the Image helper at the top of the Index.aspx view.  The helper is imported with the following directive (指示符):

<%@ Import Namespace="MvcApplication1.Helpers" %>

原谅网址http://www.asp.net/mvc/tutorials/older-versions/views/using-the-tagbuilder-class-to-build-html-helpers-cs

ASP.NET MVC- VIEW Using the TagBuilder Class to Build HTML Helpers Part 3的更多相关文章

  1. 【记录】ASP.NET MVC View 移动版浏览的奇怪问题

    ASP.NET MVC View 中的一段代码: <span id="span_Id">@Model.ID</span> 没什么问题吧,浏览器浏览正常,查看 ...

  2. ASP.Net MVC View

    ASP.Net MVC View(视图)   View视图职责是向用户提供界面.负责根据提供的模型数据,生成准备提供给用户的格式界面. 支持多种视图引擎(Razor和ASPX视图引擎是官方默认给出的, ...

  3. [转载]自定义ASP.NET MVC Html辅助方法 TagBuilder

    在ASP.NET MVC中,Html辅助方法给我们程序员带来很多方便,其重要性也就不言自明.有时候,我们不想重复地写一些HTML代码,或者MS没有提供我们想要的那个HTML标签的Html辅助方法,那么 ...

  4. ASP.NET MVC View 和 Web API 的基本权限验证

    ASP.NET MVC 5.0已经发布一段时间了,适应了一段时间,准备把原来的MVC项目重构了一遍,先把基本权限验证这块记录一下. 环境:Windows 7 Professional SP1 + Mi ...

  5. ASP.NET MVC View中的标签(tag)

    在编辑View的时候会用到各种HTML标签,如<a>,<input>,<p>等待,这些标签在ASP.NET MVC中都有对应的编程语法,它叫Razor,它是帮助我们 ...

  6. ASP.NET MVC View向Controller传值方式总结

    1:QueryString传值1)也可以使用new{}来为form的action增加querystring2)在controler里使用Request.QueryString["word&q ...

  7. ASP.NET MVC View向Controller提交数据

    我们知道使用MVC的一个很重的的用途就是把Controller和View之间进行解耦,通过控制器来调用不同的视图,这就注定了Controller和View之间的传值是一个很重的知识点,这篇博文主要解释 ...

  8. ASP.NET MVC View使用Conditional compilation symbols

    由于View(.cshtml)的运行时编译关系,在项目级别中定义的symbols是无法被直接使用的.需要在Web.config中添加compilerOptions(在View目录下的Web.confi ...

  9. ASP.NET MVC view引入命名空间

    两种方式:1,在cshtml中引入@using Admin.Models 2,在 Views 文件夹中的 Web.config 文件中添加引用如: <pages pageBaseType=&qu ...

随机推荐

  1. HTML标签总结

    HTML 基本文档 <!DOCTYPE html> <html> <head> <title>文档标题</title> </head& ...

  2. Sass中常用的函数

    字符串函数 To-upper-case() 函数将字符串小写字母转换成大写字母 To-lower-case() 函数 与 To-upper-case() 刚好相反,将字符串转换成小写字母 数字函数 S ...

  3. Python全栈开发-web框架之django

    一:web框架 什么是web框架? Web应用框架(Web application framework)是一种开发框架,用来支持动态网站.网络应用程序及网络服务的开发.这种框架有助于减轻网页开发时共通 ...

  4. lucene开发序之luke神器

    lucene是一款很优秀的全文检索的开源库,目前最新的版本是lucene4.4,关于lucene的历史背景以及发展状况,在这里笔者就不多介绍了,如果你真心想学习lucene,想必在这之前你已经对此作过 ...

  5. u-boot Makefile整体解析

    一.概述   1.理解u-boot的makefile需要的准备 linux常用命令.shell脚本基础知识.makefile脚本基础知识 2.Makefile的元素 万变不离其宗,无论工程多么复杂,文 ...

  6. 用 OUTLOOK VBA 生成 自定义文件夹 邮件列表

    Option Explicit Sub TestFolder() 'Dim outlookapp, myitem, myfolder 'Dim mailcounts As Integer ' ' 'S ...

  7. 【产品体验】喵街&飞凡

    最近O2O很火啊,我也来找几个O2O产品体验下~~~ 阿里今年5月30号上线了一款线下逛街App——喵街,号称消费者的逛街神器.阿里去年已经与银泰合作一年,探索互联网和传统实体零售合作之路,这次则免费 ...

  8. Hbase案例分析(一)

    Hbase应用场景: 1 随机读或者写 2 大数据上的高并发操作,比如每秒对PB级数据进行上千次操作.(查询,删除等操作) 3 读写均是非常简单的操作,比如没有join操作 Hbase Schema设 ...

  9. 关于ADMM的研究(一)

    关于ADMM的研究(一) 最近在研究正则化框架如何应用在大数据平台上.找到了<Distributed Optimization and Statistical Learning via the ...

  10. uva 10881 - Piotr's Ants

    这个题的突破点就在于蚂蚁不能够穿过对方,故相对位置不变: 另外,又可以把蚂蚁看成运动方向不变: 代码: #include<cstdio> #include<algorithm> ...