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