自定义HtmlHelper方法
原文:http://www.cnblogs.com/wenjiang/archive/2013/03/30/2990854.html
HtmlHelper方法是ASP.NET MVC中非常强大的特性,有了这个特性,我们就能更加随心所欲的定制自己的页面。
自定义自己的HtmlHelper方法通常有三种, 像是:
一.Razor语法
采用Razor的方式非常直观,像是这样:

@model IEnumerable<MusicShop.Models.Album>
@{
ViewBag.Title = "Index";
} @helper Truncate(string input, int length)
{
if (input.Length <= length)
{
@input;
}
else
{
@input.Substring(0, length)<text>...</text>;
}
} <h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Genre
</th>
<th>
Artist
</th>
<th>
Title
</th>
<th>
Price
</th>
<th>
AlbumArtUrl
</th>
<th></th>
</tr> @foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Genre.Name)
</td>
<td>
@Truncate(item.Artist.Name, 25);
</td>
<td>
@Truncate(item.Title, 25);
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.AlbumArtUrl)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) |
@Html.ActionLink("Details", "Details", new { id=item.AlbumId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.AlbumId })
</td>
</tr>
} </table>

@helper提示编译器,这是一个辅助方法,我们可以采用@+MethodName的方法来使用该辅助方法。
当然,在Web编程中,内联是一种不好的方式,因为它们会使得页面的加载变慢,尤其是页面的反复加载。更加常用的方式就是我们在一个命名空间里定义一个辅助方法,然后在页面中引入该辅助方法,这样页面就无需承担方法源码的加载负担。
二.扩展方法
采用这样的方式,我们通常需要新建一个文件夹,专门存放我们自定义的辅助方法(很多时候,我们自定义的辅助方法可能很多,但像是Controller,Models这样的文件夹并不适合存放这些方法),其实也就是专门为辅助方法建立一个新的命名空间。
像是这样:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc; namespace MusicShop.Helpers
{
public static class HtmlHelpers
{
public static string Truncate(this HtmlHelper helper, string input, int length)
{
if (input.Length <= length)
{
return input;
}
else
{
return input.Substring(0, length) + "...";
}
}
}
}

然后我们的页面添加以下的代码:

@model IEnumerable<MusicShop.Models.Album>
@{
ViewBag.Title = "Index";
} @using MusicShop.Helpers <h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Genre
</th>
<th>
Artist
</th>
<th>
Title
</th>
<th>
Price
</th>
<th>
AlbumArtUrl
</th>
<th></th>
</tr> @foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Genre.Name)
</td>
<td>
@Html.Truncate(item.Artist.Name, 25);
</td>
<td>
@Html.Truncate(item.Title, 25);
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.AlbumArtUrl)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) |
@Html.ActionLink("Details", "Details", new { id=item.AlbumId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.AlbumId })
</td>
</tr>
} </table>

@using是必须的,引入辅助方法所在的命名空间。对于辅助方法的处理可以看到,我们是将其当成HtmlHelper的扩展方法使用。扩展方法的使用,使得原本非常复杂的MVC设计也能具有良好的可读性,而且灵活度和复用性非常高。我刚学C#的时候,曾经对扩展方法并不是特别感冒,因为它的使用很容易"污染"被扩展类型的命名空间,使得我们在查找该类型方法的时候非常烦。但是在使用MVC的时候,尤其是HtmlHelper方法的时候,扩展方法给了我很大的震惊:如果没有扩展方法,整个代码的可读性真的很可怕!这时我想起来C#的设计理念:读着写代码。是的,使用扩展方法,我们的代码可以像是完整的句子一样被别人阅读而不会在某个艰涩的地方戛然而止。
当然,滥用语法糖是一种危险的行为,毕竟扩展方法依然存在我刚才说的毛病,尤其是考虑软件的后续发展,我们就会惊出一身冷汗:如果将来某个类型添加一个与我的扩展方法一样的方法,那么,我的代码就会出错。
所以,我们需要一种更加安全的方法。
三.Razor view
我们可以新建一个cshtml,像是下面这样:

@helper TruncateString(string input, int length)
{
if (input.Length <= length) {
@input
} else {
@input.Substring(0, length)<text>...</text>
}
}

然后就是我们的页面:

@model IEnumerable<MusicShop.Models.Album>
@{
ViewBag.Title = "Index";
} <h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table>
<tr>
<th>
Genre
</th>
<th>
Artist
</th>
<th>
Title
</th>
<th>
Price
</th>
<th>
AlbumArtUrl
</th>
<th></th>
</tr> @foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Genre.Name)
</td>
<td>
@Helpers.Truncate(item.Artist.Name, 25);
</td>
<td>
@Helpers.Truncate(item.Title, 25);
</td>
<td>
@Html.DisplayFor(modelItem => item.Price)
</td>
<td>
@Html.DisplayFor(modelItem => item.AlbumArtUrl)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id=item.AlbumId }) |
@Html.ActionLink("Details", "Details", new { id=item.AlbumId }) |
@Html.ActionLink("Delete", "Delete", new { id=item.AlbumId })
</td>
</tr>
} </table>

使用这种方法,就没有Razor语法的内联,也没有扩展方法的后顾之忧,而且我们还可以自由的添加新的自定义方法,但是,注意,Helpers.cshtml必须放在App_Code里面。
自定义HtmlHelper方法的更多相关文章
- ASP.NET MVC 之自定义HtmlHelper
前言 HtmlHelper方法为我们提供很多html标签,只需在页面调用就行了,但是微软并没有把所有的html标签都对应有了扩展方法,需要我们重新自定义HtmlHelper,来满足我们需要. 方法 如 ...
- 在 ASP.NET MVC 中创建自定义 HtmlHelper
在ASP.NET MVC应用程序的开发中,我们常碰到类似Html.Label或Html.TextBox这样的代码,它将在网页上产生一个label或input标记.这些HtmlHelper的扩展方法有些 ...
- ASP.NET MVC---自定义HtmlHelper方法
HtmlHelper方法是ASP.NET MVC中非常强大的特性,有了这个特性,我们就能更加随心所欲的定制自己的页面. 自定义自己的HtmlHelper方法通常有三种, 像是: 一.Razor语法 采 ...
- MVC教程七:扩展HtmlHelper方法
在上一篇文章的最后,列出了一些常见的HtmlHelper的方法,这些都是ASP.NET MVC已经定义好的,如果我们想自己定义一个HtmlHelper方法可以吗?答案是肯定的,那么如何自定义一个Htm ...
- validate插件深入学习-04自定义验证方法
自定义验证方法 jQuery.validator.addMethod(name,method,[,message]) name: 方法名 method: function(value,element, ...
- Jquery自定义扩展方法(二)--HTML日历控件
一.概述 研究了上节的Jquery自定义扩展方法,自己一直想做用jquery写一个小的插件,工作中也用到了用JQuery的日历插件,自己琢磨着去造个轮子--HTML5手机网页日历控件,废话不多说,先看 ...
- Jquery自定义扩展方法(一)
jquery是一款流行的JS框架,自定义JS方法,封装到Jquery中,调用起来也挺方便的,怎么写Jquery扩展方法那,网上翻阅了一部分代码,其实也挺简单的: 方式一: (jQuery.fn.set ...
- 扩展HtmlHelper方法
1.在Model中新建类MyHtmlHelperExt /// <summary> /// 扩展HtmlHelper方法 /// 扩展方法三要素:静态类,静态方法,this关键字 /// ...
- jqery validate、validate自定义验证方法 + jaery form Demo
校验规则 required:true 必输字段 remote:"check.php" 使用ajax方法调用check.php验证输入值 email:true 必须输入正确格式 ...
随机推荐
- 运行在YARN上的MapReduce应用程序(以MapReduce为例)
client作用:提交一个应用程序查看一个应用程序的运行状态(通过application master) 第一步:提交MR程序到ResourceManager,ResourceManager为这个应用 ...
- CMD 模块定义规范
在 Sea.js 中,所有 JavaScript 模块都遵循 CMD(Common Module Definition) 模块定义规范.该规范明确了模块的基本书写格式和基本交互规则. 在 CMD 规范 ...
- Technology Trader
zoj2071:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemCode=2071 题意:题意一些零件,每一个零件会有一个花费,然后用这 ...
- mysql左联右联内联
在MySQL中由于性能的关系,常常要将子查询(Sub-Queries)用连接(join)来却而代之,能够更好地使用表中索引提高查询效率. 下面介绍各种join的使用,先上图: 我们MySQL常用的为左 ...
- linux 网络栈中的queueing
这篇文章详细描述了在linux网络栈中queueing,及各种保证系统吞吐量和低延迟的方法机制.
- Git的分支与合并
在Git里面我们可以创建不同的分支,来进行调试.发布.维护等不同工作,而互不干扰.下面我们还是来创建一个试验仓库,看一下Git分支运作的台前幕后: $rm -rf test_branch_proj $ ...
- 【CF】244C Checkposts
题目需要求啥很明确了.主要思想是先计算机联通块,然后每个块内找到一个最小值(以及该值的次数).最小值和结果1,次数乘积为结果2.联通块tarjan可解. /* 427C */ #include < ...
- linux查看端口号是否被占用
etstat -anp |grep 端口号 root用户执行 netstat -ntupl n表示不查询dns t表示tcp协议 u表示udp协议 p表示查询占用的程序 l表示查询正在监听的程序 查看 ...
- MyEclipse 设置字体
过了好几年,又开始用myeclipse 都忘了, 这里贴图用于记录 1.打开window - preferences . 2.打开General-Appearance-Colors and Fon ...
- jQuery 数据 DOM 元素 核心 属性
jQuery 参考手册 - 数据 .clearQueue() 从序列中删除仍未运行的所有项目 .clearQueue(queueName) $("div").clearQueue( ...