mvc4 自定义HtmlHelper

时间:2023-03-08 20:33:17

好久没写博客了,最近只看博客不写的习惯很不好啊。

好了,最近的项目中大量的用到了表单,很多表单有特殊的编写,但是在该项目中又有很多重复的地方,这个时候若能封装成htmlhelper将大大降低工作量的。
下面给出基本的使用模型,备忘

using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web;
using System.Web.Mvc;
//引入下面的命名空间后,就可以在view中直接@出来了
namespace System.Web.Mvc
{
public static class FormHtmlHelper
{
private const string editorwidth = "100";
private const string editorheight = "100";
//给下面的方法指定第一个参数为this HtmlHelper helper,这样就可以在@Ht中
//点出来了,否则你还得@[自定义类].[你的方法]。下面的方法看上去需要传进去两个值,
//实际上只要@Html.就可以点出来了
public static MvcHtmlString NecessaryLabeler(this HtmlHelper helper,string name)
{
var ntag = new TagBuilder("span");
ntag.AddCssClass("red");
ntag.SetInnerText("*");
var nametag = new TagBuilder("span");
//tag.AddCssClass("");
nametag.SetInnerText(name);
return new MvcHtmlString(ntag.ToString()+nametag.ToString());
}
//下面的方法可以把视图的model传进去,获取值的方法看下面的lamda表达式。。。
public static MvcHtmlString DisabledEditorFor<TModel, TValue>(this HtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
object data = ModelMetadata.FromLambdaExpression<TModel, TValue>(expression, html.ViewData).Model;
if (data == null)
{
data="";
}
//to do what you want!
} }
}