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锚点

    ID模式 <h3><a href="#start">开始</a></h3> <div> 你好 <b/> &l ...

  2. jinja2 宏的简单使用总结(macro)

    Table of Contents 1. 简介 2. 用法 3. 参数和变量 4. 注意事项 4.1. macro的变量只能为如下三种: 4.2. 和block的关系: 5. 参考文档 1 简介 ji ...

  3. C++ 11 笔记 (一) : lambda

    时至今日都是我咎由自取,错就是错,与任何人无关.掉进C++98的各种坑里无法自拔的抖M感,让我选择了华丽丽的无视C++11,导致今日面对开源的代码到各种看不懂的地步,一入C++深似海,我今天愿意承担一 ...

  4. hdu 1116

    欧拉回路,利用并查集来实现: 代码: #include<cstdio> #include<cstring> #include<vector> using names ...

  5. 关于keil中data,idata,xdata,pdata,code的问题

    转自关于keil中data,idata,xdata,pdata,code的问题 ‍从数据存储类型来说,8051系列有片内.片外程序存储器,片内.片外数据存储器,片内程序存储器还分直接寻址区和间接寻址类 ...

  6. [ecmall]Ecmall 后台添加模板编辑区

    例如,想把品牌/index.php?app=brand页面做成可编辑的. 首先,找到后台admin\includes\menu.inc.php第61行 'template' => array( ...

  7. 移动应用产品开发-android开发(二)

    这段时间实在太忙了,也没什么精力来写博客,还是没养成写博客的习惯,还是得记载下来,不然时间久了就忘记了. 早上一大早就来公司了,趁还早,拟定今天的工作内容和计划后,赶紧记载点东西. 最近做androi ...

  8. 禁止form表单回车键进行提交

    使用EasyUI的时候,我们会给一个datagrid添加一个搜索栏,但是这个搜索栏的form,我们一般使用ajax向服务器提交数据,因此在这样一个环境下可以考虑禁止用户按回车键(Enter)提交.代码 ...

  9. 【网络流24题】 No.12 软件补丁问题(最小转移代价 最短路)

    [题意] T 公司发现其研制的一个软件中有 n 个错误, 随即为该软件发放了一批共 m 个补丁程序. 每一个补丁程序都有其特定的适用环境, 某个补丁只有在软件中包含某些错误而同时又不包含另一些错误时才 ...

  10. Excel数据链接取消

    Excel数据链接取消 2013-9-14 学校里弄来学生的成绩单,想去掉原来高一的学号,但是一删除,后面的成绩数据就一同消失,如以下两图对比所示. 删除第一列前 删除第一列后 此问题不知道怎么描述, ...