MVC中的自定义控件

MVC中的控件都是HtmlHelper的扩展方法(不了解扩展方?法请阅读扩展方法),比如@Html.ActionLink,F12可以看到它是这样写的:

 public static MvcHtmlString ActionLink(this HtmlHelper htmlHelper, string linkText, string actionName);

同理,自定义控件也是写HtmlHelper的扩展方法。

例:

实现一个显示消息的控件

代码:写一个扩展方法,第一个参数用this修饰符类型是HtmlHelper,第二个参数是消息标题,第三个参数是消息内容,如下

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;

namespace System.Web.Mvc.Html
{
    public static class MessageLabelExtensions
    {
        public static HtmlString MessageLable(this HtmlHelper htmlHelper, string title, string message)
        {
            StringBuilder strHtml = new StringBuilder();
            strHtml.Append("<div>");
            strHtml.Append("<h3>"+title+"</h3>");
            strHtml.Append("<p>"+message+"</p>");
            strHtml.Append("</div>");
            return new HtmlString(strHtml.ToString());
        }
    }
}

完成了,可以在view中使用这个控件了!

@Html.MessageLable("好消息!", "你好,这是测试消息!")

就是这么简单!

转载于:https://www.cnblogs.com/LLLLoveLLLLife/p/3623586.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值