asp.net mvc Htmlhelper简单扩展
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")
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· 【自荐】一款简洁、开源的在线白板工具 Drawnix