ASP.NET MVC---自定义HtmlHelper方法
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(, 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, );
</td>
<td>
@Truncate(item.Title, );
</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(, 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, );
</td>
<td>
@Html.Truncate(item.Title, );
</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(, 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, );
</td>
<td>
@Helpers.Truncate(item.Title, );
</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里面。
ASP.NET MVC---自定义HtmlHelper方法的更多相关文章
- asp.net mvc 自定义pager封装与优化
asp.net mvc 自定义pager封装与优化 Intro 之前做了一个通用的分页组件,但是有些不足,从翻页事件和分页样式都融合在后台代码中,到翻页事件可以自定义,再到翻页和样式都和代码分离, 自 ...
- ASP.NET MVC 自定义路由中几个需要注意的小细节
本文主要记录在ASP.NET MVC自定义路由时,一个需要注意的参数设置小细节. 举例来说,就是在访问 http://localhost/Home/About/arg1/arg2/arg3 这样的自定 ...
- Asp.net Mvc 自定义Session (二)
在 Asp.net Mvc 自定义Session (一)中我们把数据缓存工具类写好了,今天在我们在这篇把 剩下的自定义Session写完 首先还请大家跟着我的思路一步步的来实现,既然我们要自定义Ses ...
- Asp.net mvc 自定义全局的错误事件HandleErrorAttribute无效
Asp.net mvc 自定义全局的错误事件HandleErrorAttribute,结果无效, 原因: 1.没有在RegisterGlobalFilters 里面添加或者你要的位置添加. 2.你把这 ...
- Asp.net mvc 中Action 方法的执行(一)
[toc] 在 Aps.net mvc 应用中对请求的处理最终都是转换为对某个 Controller 中的某个 Action 方法的调用,因此,要对一个请求进行处理,第一步,需要根据请求解析出对应的 ...
- ASP.NET MVC 自定义Razor视图WorkContext
概述 1.在ASP.NET MVC项目开发的过程中,我们经常需要在cshtml的视图层输出一些公用信息 比如:页面Title.服务器日期时间.页面关键字.关键字描述.系统版本号.资源版本号等 2.普通 ...
- asp.net MVC 自定义模型绑定 从客户端中检测到有潜在危险的 Request.QueryString 值
asp.net mvc 自定义模型绑定 有潜在的Requset.Form 自定义了一个模型绑定器.前端会传过来一些敏感字符.调用bindContext. valueProvider.GetValue( ...
- ASP.NET MVC自定义验证Authorize Attribute(包含cookie helper)
前几天Insus.NET有在数据库实现过对某一字段进行加密码与解密<使用EncryptByPassPhrase和DecryptByPassPhrase对MS SQLServer某一字段时行加密和 ...
- 转:自定义ASP.NET MVC Html辅助方法
在ASP.NET MVC中,Html辅助方法给我们程序员带来很多方便,其重要性也就不言自明.有时候,我们不想重复地写一些HTML代码,或者MS没有提供我们想要的那个HTML标签的Html辅助方法,那么 ...
- 【MVC】自定义ASP.NET MVC Html辅助方法
在ASP.NET MVC中,Html辅助方法给我们程序员带来很多方便,其重要性也就不言自明.有时候,我们不想重复地写一些HTML代码,或者MS没有提供我们想要的那个HTML标签的Html辅助方法,那么 ...
随机推荐
- c语言中->的一个作用
为了使用方便和直观,c语言中结构体指针带成员(*p).num可以用p->num来代替. ->称为指向运算符:
- find the closest sum to a target value
problem: given an array of integers including positive and negative, a target value. find 2 numbers ...
- ios 中NSArray
// #import <Foundation/Foundation.h> #import "Animal.h" int main(int argc, const cha ...
- sysbench使用教程【转载】
水晶命匣 2016-08-16 20:02 一.环境描述 此次使用的虚拟机环境如下所示: CPU:双核 2.4GHz 内存:4 GB 硬盘:120 GB IP:192.168.21.129 操作系统: ...
- git conflict
https://wiki.52north.org/bin/view/Documentation/ResolveMergeConflictsInGitEclipse Note that you can ...
- java问题诊断
http://techblog.youdao.com/?p=961 http://linuxtools-rst.readthedocs.org/zh_CN/latest/advance/03_opti ...
- Django urls常用匹配语法
url from django.conf.urls import url from . import views urlpatterns = [ url(r'^articles/2003/$', vi ...
- Toolbar Painter 工具条制作
工具条制作工具(ToolBarPainter2013.exe),专为程序猿设计,界面开发必备.当用VC编程制作工具条时,需要为工具栏上每一个button添加图标,是一件极其繁琐的事情,该工具可利用已有 ...
- Echarts自适应浏览器大小
var myChart = echarts.init(document.getElementById('sitesChar')); var option = { title : { text: 'No ...
- WPF Template模版之DataTemplate与ControlTemplate【一】
WPF Template模版之DataTemplate与ControlTemplate[一] 标签: Wpf模版 2015-04-19 11:52 510人阅读 评论(0) 收藏 举报 分类: -- ...