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. php中将地址生成迅雷快车旋风链接的代码

    function zhuanhuan() { $urlodd=explode('//',$_GET["url"],2);//把链接分成2段,//前面是第一段,后面的是第二段 $he ...

  2. PHP 冒泡排序法

    <?php // 冒泡排序法:将一个数组中的值按照从小到大的顺 序排序 $arr = array(33, 1, 4, 5, 2, 3, 7, 9, 8, 99); $len = count($a ...

  3. 远程连接sql server 数据库的方法

    今天找了半天,终于解决了如何从本地连接到远程sql server服务器的方法. 1.首先确保打开远程服务器的sql server配置管理器,确保TCP/IP协议开启 2.WebConfig的连接字符格 ...

  4. 《C和指针》章节后编程练习解答参考——第9章

    9.1 #include <stdio.h> #include <ctype.h> #include <string.h> #define N 100 int ma ...

  5. MINA的session.close

    现象:客户端session.close之后,并没有提出,客户端程序一直hold在那里: 解决:调用了session.getService().dispose(false)方法后,客户端程序完成了退出 ...

  6. 关于Java(JDBC连接数据库)

    Processing SQL Statements with JDBC 处理JDBC中的SQL语句 这节主要是 JDBC 与数据库交互的基本步骤 JDBC的基石是DriverManager,通过它,J ...

  7. JQuery replace 替换全部

    天在做写个程序时遇到需要替换的功能,可是一开始用jquery的replace时,发现只替换到第一个.最后没办法,只好用正则表达式来例如下面   re = new RegExp("{thisc ...

  8. Bootstrap 分页插件 ajax获取数据显示

    Bootstrap 分页插件 ajax获取数据显示 标签(空格分隔): bootstrap 文章的内容是使用bootstrap-paginator进行分页,使用ajax获取后台数据.渲染. 1. 版本 ...

  9. uva 1453 - Squares

    旋转卡壳算法: 直接在这个上面粘的模板 主要用途:用于求凸包的直径.宽度,两个不相交凸包间的最大距离和最小距离··· 这题就是求凸包的直径 #include <cstdio> #inclu ...

  10. Spring MVC注解冲突

    SpringMVC+MyBatis - 7 Spring自动扫描注解类的冲突问题 http://www.blogjava.net/crazycy/archive/2014/07/12/415738.h ...