Jen

.NET 4.0 Cleaner Markup

寫.NET Web ap比較正統的人,都習慣用上大量的Web Server Control,

 

有時會很討厭naming container的命名機制,

 

一層包一層的結果,Render出來的ClientID可能會變成

 

ctl00_ContentPlaceholder1_ListView1_ctrl0_Label1

 

如此如此,在寫Java Script或者套CSS,真的很不方便,這也是我自已有時候蠻討厭的地方。

(所以最近比較偏愛ASP.NET MVC !!)

 

but, .NET 4.0 有聽到大家的complaints喔, let’s take~

 

 

 

.NET 4.0 主要是在Control 這個base class加上一個ClientIDMode的屬性,

 

主要有4種摸式,AutoID'、Predictable、Static、Inherit

 

--> ServerSide Example

<asp:Content ID="main" ContentPlaceHolderID="mainContent" runat="server">
      <asp:Label ID="lbTest" runat="server" />
</asp:Content>
--> ClientSide Examples translate from ServerSide Example for 4 modes 
  • AutoID—Renders the output as in .NET 3.5 (auto-generated IDs which will still render prefixes like ctrl00 for compatibility)
    • <span id="ct100_main_lbTest">test</span>
  • Predictable (Default)— Trims any “ctl00” ID string and if a list/container control concatenates child ids (example: id=”ParentControl_ChildControl”)
    • <span id="main_lbTest">test</span>
  • Static—Hands over full ID naming control to the developer – whatever they set as the ID of the control is what is rendered (example: id=”JustMyId”)
    • <span id="lbTest">test</span>
  • Inherit—Tells the control to defer to the naming behavior mode of the parent container control
    • 繼承parent container的設定,如果都沒有就是default.

 

你可以在Web.config做設定,針對你整個solution,

<system.web>
	<pages clientIDMode="Static" />
</system.web>

 

針對某頁做設定

<%@ Page Language="C#" ClientIDMode="Static" %>

 

針對某項Control 做設定

<asp:Label ID="lb_Test" runat="server" />

 

 

還有一招更酷的,假設你有一個Data Source,

ID Code
1 CShape
2 Vb
3 Java

 

 

再假設ListView的Data Source是上面那個表格,
你可以指定ClientIDRowSuffix="Code">,值為Data Source的某1個欄位
<asp:ListView ID="airports" runat="server" ClientIDRowSuffix="Code">
   <itemTemplate>
	<li id="airport" runat="server">
		<%#Eval("Code") %>
	</li>
   </itemTemplate>
</asp:ListView>

 

Render出來會變成

<li id="airports_airport_CShape">CShape</li>
<li id="airports_airport_Vb">Vb</li>
<li id="airports_airport_Java">Java</li>

 

ClientID是不是比較好掌握了~~

 

參考ScottGu的,寫的蠻清楚的喔~參考ScottGu's Blog

0 意見: