原文: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方法的更多相关文章

  1. ASP.NET MVC 之自定义HtmlHelper

    前言 HtmlHelper方法为我们提供很多html标签,只需在页面调用就行了,但是微软并没有把所有的html标签都对应有了扩展方法,需要我们重新自定义HtmlHelper,来满足我们需要. 方法 如 ...

  2. 在 ASP.NET MVC 中创建自定义 HtmlHelper

    在ASP.NET MVC应用程序的开发中,我们常碰到类似Html.Label或Html.TextBox这样的代码,它将在网页上产生一个label或input标记.这些HtmlHelper的扩展方法有些 ...

  3. ASP.NET MVC---自定义HtmlHelper方法

    HtmlHelper方法是ASP.NET MVC中非常强大的特性,有了这个特性,我们就能更加随心所欲的定制自己的页面. 自定义自己的HtmlHelper方法通常有三种, 像是: 一.Razor语法 采 ...

  4. MVC教程七:扩展HtmlHelper方法

    在上一篇文章的最后,列出了一些常见的HtmlHelper的方法,这些都是ASP.NET MVC已经定义好的,如果我们想自己定义一个HtmlHelper方法可以吗?答案是肯定的,那么如何自定义一个Htm ...

  5. validate插件深入学习-04自定义验证方法

    自定义验证方法 jQuery.validator.addMethod(name,method,[,message]) name: 方法名 method: function(value,element, ...

  6. Jquery自定义扩展方法(二)--HTML日历控件

    一.概述 研究了上节的Jquery自定义扩展方法,自己一直想做用jquery写一个小的插件,工作中也用到了用JQuery的日历插件,自己琢磨着去造个轮子--HTML5手机网页日历控件,废话不多说,先看 ...

  7. Jquery自定义扩展方法(一)

    jquery是一款流行的JS框架,自定义JS方法,封装到Jquery中,调用起来也挺方便的,怎么写Jquery扩展方法那,网上翻阅了一部分代码,其实也挺简单的: 方式一: (jQuery.fn.set ...

  8. 扩展HtmlHelper方法

    1.在Model中新建类MyHtmlHelperExt /// <summary> /// 扩展HtmlHelper方法 /// 扩展方法三要素:静态类,静态方法,this关键字 /// ...

  9. jqery validate、validate自定义验证方法 + jaery form Demo

    校验规则 required:true  必输字段 remote:"check.php"  使用ajax方法调用check.php验证输入值 email:true  必须输入正确格式 ...

随机推荐

  1. win7+ubuntu双系统安装方法

    转自win7+ubuntu双系统安装方法 前段时间又安装一下win7+ubuntu双系统,过段时间就会忘记,这次自己写下来,以便以后查看. 1.      先准备一个分区来安装ubuntu.在win7 ...

  2. BZOJ 3122 随机数生成器

    http://www.lydsy.com/JudgeOnline/problem.php?id=3122 题意:给出p,a,b,x1,t 已知xn=a*xn-1+b%p,求最小的n令xn=t 首先,若 ...

  3. C++ Virtual详解(注意函数被隐藏的问题)

    Virtual是C++ OO机制中很重要的一个关键字.只要是学过C++的人都知道在类Base中加了Virtual关键字的函数就是虚拟函数(例如函数print),于是在Base的派生类Derived中就 ...

  4. android中保存一个ArrayList到SharedPreferences的方法

    保存: public static boolean saveArray() { SharedPrefernces sp=SharedPrefernces.getDefaultSharedPrefern ...

  5. SQL也能玩递归

    最近在做项目的时候遇到一个表,将省市区都放到一个表里存储,通过父ID字段来表示省市区的关系. 创建表语句 CREATE TABLE [dbo].[Table_6]( [id1] [int] NOT N ...

  6. .config-20150410

    ## Automatically generated file; DO NOT EDIT.# OpenWrt Configuration#CONFIG_MODULES=yCONFIG_HAVE_DOT ...

  7. ASP.NET 中Request.QueryString 中的key

    在ASP.net中 的Key是可能为null的,例如在如下的Url中 http://localhost:14546/Home/Index?a 有一个key=null 其value是a,以前一直以为ke ...

  8. 浅谈Redis及其安装配置

    一.Redis的介绍 二.Redis的安装配置 三.Redis的配置文件说明 四.Redis的简单操作 简介: Redis是一个开源的使用ANSI C语言编写.支持网络.可基于内存亦可持久化的日志型. ...

  9. Linux下高效编写Shell——shell特殊字符汇总

    Linux下无论如何都是要用到shell命令的,在Shell的实际使用中,有编程经验的很容易上手,但稍微有难度的是shell里面的那些个符号,各种特殊的符号在我们编写Shell脚本的时候如果能够用的好 ...

  10. [转]让程序在崩溃时体面的退出之CallStack

    原文地址:http://blog.csdn.net/starlee/article/details/6618849 在我的那篇<让程序在崩溃时体面的退出之Unhandled Exception& ...