• ASP.NET MVC Razor HtmlHelper扩展和自定义控件


    先看示例代码:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Web;
     5 using System.Web.Mvc;
     6 using System.Web.Routing;
     7 
     8 namespace MvcApplicationWeb
     9 {
    10     public static class HtmlExtensions
    11     {
    12         public static MvcHtmlString TestHtml(this HtmlHelper htmlHelper)
    13         {
    14             return MvcHtmlString.Create("<div style='font-size:18px;'>MyTestHtmlHelper</div>");
    15         }
    16 
    17         public static string TestHtml(this HtmlHelper htmlHelper, string value)
    18         {
    19             return String.Format("<div>{0}</div>", value);
    20         }
    21 
    22         public static MvcHtmlString JSHtml(this HtmlHelper htmlHelper)
    23         {
    24             return MvcHtmlString.Create("<script type="text/javascript">alert('JSHtmlTest');</script>");
    25         }
    26 
    27         public static string Label(this HtmlHelper helper, int target, string text)
    28         {
    29             TagBuilder tagBuilder = new TagBuilder("label")
    30             {
    31                 InnerHtml = target.ToString()
    32             };
    33             tagBuilder.MergeAttribute("for", text);
    34             return tagBuilder.ToString(TagRenderMode.Normal);
    35         }
    36     }
    37 }

    上面是扩展类的代码,类名要写成XXExtensions,不然不能在前台使用的。

    上面自定义了三个控件,如果返回是MvcHtmlString 将会在页面已HTML形式显示,如果返回是string就会已字符显示

    同时可以用TagBuilder来构建HTML

    前台代码如下:

     1 @using MvcApplicationWeb;
     2 @{
     3     ViewBag.Title = "主页";
     4 }
     5 @section featured {
     6     <section class="featured">
     7         <div class="content-wrapper">
     8             <hgroup class="title">
     9                 <h1>@ViewBag.Title.</h1>
    10                 <h2>@ViewBag.Message</h2>
    11             </hgroup>
    12             <p>
    13                 若要了解有关 ASP.NET MVC 的详细信息,请访问
    14                 <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>。
    15                 该页提供 <mark>视频、教程和示例</mark> 以帮助你充分利用 ASP.NET MVC。
    16                 如果你对 ASP.NET MVC 有任何疑问,请访问
    17                 <a href="http://forums.asp.net/1146.aspx/1?MVC" title="ASP.NET MVC Forum">我们的论坛</a>18             </p>
    19         </div>
    20     </section>
    21 }
    22 <h3>下面是我们的建议:</h3>
    23 @Html.TestHtml()
    24 @Html.TestHtml("TestHtml")
    25 @Html.JSHtml()
    26 @Html.Label(1,"2")

    前台注意的就是要引用命名空间!

  • 相关阅读:
    Mybatis框架学习02
    第四周学习进度
    第四周安卓开发学习总结(2)
    第四周安卓开发学习总结(1)
    使用Python进行疫情数据爬取
    使用Jsoup进行疫情数据爬取
    Mybatis框架学习01
    第三周学习进度
    第三周安卓开发学习总结
    全国疫情统计地图可视化(2)——实现数据下钻
  • 原文地址:https://www.cnblogs.com/stalwart/p/3299035.html
Copyright © 2020-2023  润新知