[C#][ASP.NET MVC]簡單好用TagBuilder

  • 8967
  • 0
  • C#
  • 2010-01-15

[C#][ASP.NET MVC]簡單好用TagBuilder

當我們要自行建置HtmlHelper,由於ASP.NET MVC Framework提供了相當方便的TagBuilder Class

讓我們可以更簡單來建置Html Tag,自己實做記錄一下。

 

未使用TagBuilder,

image

改用TagBuilder


 public static String Tagbtextarea(this HtmlHelper helper, String cols,
            String rows, String id, String name, String text)
        {
            // Create tag builder
            var Htmlbuilder = new TagBuilder("textarea");           
            // Add attributes                   
            Htmlbuilder.MergeAttribute("cols", cols);
            Htmlbuilder.MergeAttribute("rows", rows);
            Htmlbuilder.MergeAttribute("name", name);
            // Create valid id          
            Htmlbuilder.GenerateId(id);

            Htmlbuilder.InnerHtml = text;        
            // Render tag
            return Htmlbuilder.ToString(TagRenderMode.Normal);
        }

 <h2>Index</h2>
  <%-- <%=Html.Mytextarea("最新消息:好用的TabBuilder") %>--%>
   <!-- Calling helper without HTML attributes -->
   <%= Html.Tagbtextarea("40","5","news","news","最新消息:好用的TabBuilder") %>

View

image

TagRenderMode主要控制Html Tag建置方式

image 

簡單測試看看結果如何


public static String TagbLabel(this HtmlHelper helper, String id, String text)
        {
            var Htmlbuilder = new TagBuilder("Label");
            Htmlbuilder.InnerHtml = text;
            Htmlbuilder.MergeAttribute("for", id);
            return Htmlbuilder.ToString(TagRenderMode.Normal);
        }

View


<%=Html.TagbLabel ("sex", "男")%>

相關結果

Normal==ToString()


<Label for="sex">男</Label>

StratTag


<Label for="sex">

EndTag


</Label>

SelfClosing


<Label for="sex" />

 

參考

Using the TagBuilder Class to Create HTML Helpers (C#)

TagRenderMode Enumeration