Cleaner ClientID's with ASP.NET 4.0
- by amaniar
Normal
0
false
false
false
EN-US
X-NONE
HI
/* Style Definitions */
table.MsoNormalTable
{mso-style-name:"Table Normal";
mso-tstyle-rowband-size:0;
mso-tstyle-colband-size:0;
mso-style-noshow:yes;
mso-style-priority:99;
mso-style-qformat:yes;
mso-style-parent:"";
mso-padding-alt:0in 5.4pt 0in 5.4pt;
mso-para-margin-top:0in;
mso-para-margin-right:0in;
mso-para-margin-bottom:10.0pt;
mso-para-margin-left:0in;
line-height:115%;
mso-pagination:widow-orphan;
font-size:11.0pt;
mso-bidi-font-size:10.0pt;
font-family:"Calibri","sans-serif";
mso-ascii-font-family:Calibri;
mso-ascii-theme-font:minor-latin;
mso-fareast-font-family:"Times New Roman";
mso-fareast-theme-font:minor-fareast;
mso-hansi-font-family:Calibri;
mso-hansi-theme-font:minor-latin;}
A common complain we have had when using ASP.NET web forms is the inability to control the ID attributes being rendered in the HTML markup when using server controls.
Our Interface Engineers want to be able to predict the ID’s of controls thereby having more control over their client side code for selecting/manipulating elements by ID or using CSS to target them.
While playing with the just released VS2010 and .NET 4.0 I discovered some real cool improvements. One of them is the ability to now have full control over the ID being rendered for server controls.
ASP.NET 4.0 controls now have a new ClientIDMode property which gives the developer complete control over the ID’s being rendered making it easy to write JavaScript and CSS against the rendered html.
By default the ClientIDMode is set to Predictable which results in clean and predictable ID’s by concatenating the ID’s of the Parent and child controls. So the following markup:
<asp:Content ID="ParentContainer" ContentPlaceHolderID="MainContentPlaceHolder" runat="server">
<asp:Label runat="server" ID="MyLabel">My Label</asp:Label>
</asp:Content>
Will render:
<span id="ParentContainer_MyLabel">My Label</span>
Instead of something like this: (current)
<span id="ct100_ParentContainer_MyLabel">My Label</span>
Other modes include AutoID (renders ID’s like it currently does in .NET 3.5), Static (renders the ID exactly as specified in the code) and Inherit (defers the mode to the parent control).
So now I can write my jQuery selector as:
$(“ParentContainer_MyLabel”).text(“My new Text”);
Instead of:
$(‘<%=this. MyLabel.ClientID%>’).text(“My new Text”);
Scott Mitchell has a great article about this new feature:
http://bit.ly/ailEJ2
Am excited about this and some other improvements. Many thanks to the ASP.NET team for Listening!