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")

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

posted @ 2013-09-03 16:38  Jones.Zhao  阅读(2493)  评论(1编辑  收藏  举报