using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace WebApplication1.MyHtmlHelper
{
public static class MyHtmlHelper
{
//页面渲染结果:
//<span>我扩展的Label,自动生成Span标签</span>
//把标签名都显示(直接将内容显示)
public static string MyHtmlLable1(this HtmlHelper html,string lableName)
{
return string.Format("<span>{0}</span>",lableName);
}
public static HtmlString MyHtml(this HtmlHelper html, string value)
{
return new HtmlString(value);
}
//页面渲染结果:
//span标签
public static HtmlString MyHtmlLable2(this HtmlHelper html, string lableName)
{
return MyHtml(html,string.Format("<span>{0}</span>", lableName));
}
//页面渲染结果:
//input标签
public static HtmlString MyTextBox(this HtmlHelper html,string content)
{
return MyHtml(html,string.Format("<input type='type' value='{0}'/>",content));
}
}
}
@using WebApplication1.MyHtmlHelper
@{
ViewBag.Title = "Test";
}
<h2>Test</h2>
@*结果:<span>我扩展的Label,自动生成Span标签</span>*@
@Html.MyHtmlLable1("我扩展的Label,自动生成Span标签") <br />
@*结果:我扩展的Label,自动生成Span标签*@
@Html.MyHtmlLable2("我扩展的Label,自动生成Span标签") <br />
@*结果:span标签测试*@
@Html.MyHtml("span标签测试") <br />
@*textbox*@
@Html.MyTextBox("textbox") <br />
所有标签定义方法:
public static string SelfDefineTagString(this HtmlHelper helper, string tagName, string id, string name, string className,string value, string style)
{
//创建标签
TagBuilder tb = new TagBuilder(tagName);
//定义标签id
tb.GenerateId(id);
//定义标签name
tb.MergeAttribute("name", name);
//定义标签class
tb.AddCssClass(className);
//定义标签样式
tb.MergeAttribute("style", style);
//定义标签内容
tb.SetInnerText(value);
return tb.ToString();
}
public static HtmlString SelfDefineTag(this HtmlHelper helper, string tagName, string id, string name, string className,string value, string style)
{
return new HtmlString(SelfDefineTagString(helper, tagName, id, name, className, value, style));
}
html调用方法:
@Html.SelfDefineTag("p", "test", "test", "test", "p标签", "color:red;background:#ccc;width:100px;text-align:center")