在使用MVC开发过程当中发如今View中须要一些自定义的方法,之前在webfrom开发是则是使用一个静态类,在里面编辑许多常用的方法来解决的。如今发如今MVC里面能够自定义扩展的HtmlHelper方法,具体操做以下:
1.新建一个类
能够在项目中添加一个文件夹,命名为Helpers,在这个文件夹中能够添加各个类型的扩展类。下面咱们添加一个文本处理扩展类,命名TextHelper.cs。html
using System; using System.Collections.Generic;
using System.Linq; using System.Web;
using System.Web.Mvc;web
namespace System.Web.Mvc
{
public static class ExTextHelper
{
public static string DateFormate(this HtmlHelper html, DateTime time)
{
return String.Format(@"{0:yyyy-MM-dd HH:mm}");
}
}
}this
注意:把该类的命名空间改成 namespace System.Web.Mvc,这样就能够在页面中使用该扩展方法了,否则该扩展方法是不会被识别的。
2.使用方法
在页面中引用:@Html.DateFormate(date)spa