mvc4 自定义HtmlHelper

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

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

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!
        }
        
    }
}
相关文章
相关标签/搜索