ASP.NET MVC- VIEW Using the TagBuilder Class to Build HTML Helpers Part 3
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的更多相关文章
- 【记录】ASP.NET MVC View 移动版浏览的奇怪问题
ASP.NET MVC View 中的一段代码: <span id="span_Id">@Model.ID</span> 没什么问题吧,浏览器浏览正常,查看 ...
- ASP.Net MVC View
ASP.Net MVC View(视图) View视图职责是向用户提供界面.负责根据提供的模型数据,生成准备提供给用户的格式界面. 支持多种视图引擎(Razor和ASPX视图引擎是官方默认给出的, ...
- [转载]自定义ASP.NET MVC Html辅助方法 TagBuilder
在ASP.NET MVC中,Html辅助方法给我们程序员带来很多方便,其重要性也就不言自明.有时候,我们不想重复地写一些HTML代码,或者MS没有提供我们想要的那个HTML标签的Html辅助方法,那么 ...
- ASP.NET MVC View 和 Web API 的基本权限验证
ASP.NET MVC 5.0已经发布一段时间了,适应了一段时间,准备把原来的MVC项目重构了一遍,先把基本权限验证这块记录一下. 环境:Windows 7 Professional SP1 + Mi ...
- ASP.NET MVC View中的标签(tag)
在编辑View的时候会用到各种HTML标签,如<a>,<input>,<p>等待,这些标签在ASP.NET MVC中都有对应的编程语法,它叫Razor,它是帮助我们 ...
- ASP.NET MVC View向Controller传值方式总结
1:QueryString传值1)也可以使用new{}来为form的action增加querystring2)在controler里使用Request.QueryString["word&q ...
- ASP.NET MVC View向Controller提交数据
我们知道使用MVC的一个很重的的用途就是把Controller和View之间进行解耦,通过控制器来调用不同的视图,这就注定了Controller和View之间的传值是一个很重的知识点,这篇博文主要解释 ...
- ASP.NET MVC View使用Conditional compilation symbols
由于View(.cshtml)的运行时编译关系,在项目级别中定义的symbols是无法被直接使用的.需要在Web.config中添加compilerOptions(在View目录下的Web.confi ...
- ASP.NET MVC view引入命名空间
两种方式:1,在cshtml中引入@using Admin.Models 2,在 Views 文件夹中的 Web.config 文件中添加引用如: <pages pageBaseType=&qu ...
随机推荐
- shutdown computer in ad and ou
1. powershell Shutdown-computer –computername (gc c:\temp\serverlist.txt) –force –throttlelimit 10 h ...
- bootstrap兼容IE8 解决办法
bootstrap有使用CSS3,所以ie9以下浏览器不会很顺畅.IE9以下的兼容性不是很好.IE本身就是怪胎,就搞一些和外界标准不一致.搞得web开发考虑这考虑那的兼容性,蛋疼! 基本上css3的没 ...
- Session里的对象是不可靠的!
最近在做Database课程的final project,foodiePharos, 重新认识了JSP里容易出现的一些问题. 比如我们这个项目使用了JPA,就涉及到entity对象的状态问题,Enti ...
- Analysis Guidelines
This section describes some best practices for analysis. These practices come from experience of ana ...
- 【UVA 1395】 Slim Span (苗条树)
[题意] 求一颗生成树,满足最大边和最小边之差最小 InputThe input consists of multiple datasets, followed by a line containin ...
- 使用HttpClient向服务器发送restful post请求
直接上代码: public class RestClient { public static void main(String[] args) { String url = "http:// ...
- UVA 11426 GCD Extrme (Ⅲ)
给定一个整数N(1<N<=4000000)的整数求∑GCD(i,j)i=1,2,3....j-1,2<=j<=n的值.参考了一下网上的题解,复述一下我理解后的思路,加深理解: ...
- SPRING IN ACTION 第4版笔记-第二章WIRING BEANS-007-以set方法注入<property>\p-namespace\util-space
一.注入简单属性 package soundsystem.properties; import org.springframework.beans.factory.annotation.Autowir ...
- 2-3 tree使用
The 2-3 tree is also a search tree like the binary search tree, but this tree tries to solve the pro ...
- jni.h头文件详解一
1.jni.h头文件路径: /usr/lib/jvm/jdk_1.6.0_43/include/jni.h 2.jni.h头文件组成分析图: 3.下面通过上图进行分析讲解jni.h头文件. 一. jn ...