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 ...
随机推荐
- php中getimagesize函数的用法
php获取图片信息getimagesize,php自带函数.获取图片的类型,尺寸的方法有许多,该函数仅是方法之一. getimagesize() 函数将测定任何 GIF,JPG,PNG,SWF,SWC ...
- ConfigParser---python
# !/usr/bin/python # Filename:tcfg.py import ConfigParser config = ConfigParser.ConfigParser() confi ...
- JVM内存管理基本概念
java中是否存在内存泄露? 在Java中,内存泄漏就是存在一些被分配的对象,这些对象有下面两个特点,首先,这些对象是可达的,即在有向图中,存在通路可以与其相连:其次,这些对象是无用的,即程序以后不会 ...
- iOS项目架构文档
设计的项目架构主要引用MVVM+MVC架构,并以功能模块分级.以下为目录结构. 初级目录: 我们只需要关注SGZH文件夹下的目录,其他为Xcode管理的目录.可以看到此目录为项目初级目录,我们开发过程 ...
- Firebird/InterBase内置函数使用说明
Firebird/InterBase内置函数使用说明(转自:圣域天堂) 2008-10-12 20:56 加*号为FB2.0加入的函数 整理:剑雷(jianlei) 2006-10-13 1. COU ...
- C语言利用va_list、va_start、va_end、va_arg宏定义可变参数的函数
在定义可变参数的函数之前,先来理解一下函数参数的传递原理: 1.函数参数是以栈这种数据结构来存取的,在函数参数列表中,从右至左依次入栈. 2.参数的内存存放格式:参数的内存地址存放在内存的堆栈段中,在 ...
- 通过本地加载ga.js文件提高Google Anlytics性能
Google Anlytics 分析代码是异步加载的,一般来讲不会影响网页性能,但是技术部的网页性能报告里老是提到ga.js的状态为Aborted,说明ga虽然是异步跟踪,但某些情况下对网页性能与加载 ...
- Django 数据库查询优化
Django数据层提供各种途径优化数据的访问,一个项目大量优化工作一般是放在后期来做,早期的优化是“万恶之源”,这是前人总结的经验,不无道理.如果事先理解Django的优化技巧,开发过程中稍稍留意,后 ...
- PHP传引用报错(5.4版本)
php5.3系列版本以及以前版本,传引用没有什么问题,升级到php5.4以后,传引用的地方,全报错 Fatal error: Call-time pass-by-reference has been ...
- 【BZOJ 3122】 [Sdoi2013]随机数生成器 (BSGS)
3122: [Sdoi2013]随机数生成器 Time Limit: 10 Sec Memory Limit: 256 MBSubmit: 1442 Solved: 552 Description ...