Friday, May 28, 2010

ClientIDMode in ASP.NET 4.0

One of the more anticipated features of ASP.NET 4.0 – is the new ClientIDMode property, which can be used to force controls to generate clean Client IDs that don’t follow ASP.NET’s munged NamingContainer ID conventions. To be clear, NamingContainer IDs are necessary for complex controls and pages that nest many things inside of a single context, but for most application level Web design scenarios those munged IDs get in the way and don’t provide a lot of value.

The munged IDs affect all sorts of development scenarios from design and CSS styling where ID haven’t been predictable for #id styling:

#ctl00_content_txtName 
{
font-weight: bold;
}



vs the more expected:



#txtName
{
font-weight: bold;
}



And even more so there’s the whole nightmare of ClientIds in script pages where code like this:



<script type="text/javascript">
var txtName = $("<%= txtName.ClientID %>");
var txtTitle = $("[id$=_txtTitle]");
</script>



or some other pre-generation code is necessary to get client id’s properly referenced in script code.



ClientIDMode


In prior versions of ASP.NET you had to live with the problem or work around with various hacks. In ASP.NET 4.0 things get a little easier via the new ClientIDMode property which allows you to specify exactly how a ClientID is generated.



The idea is simple: you get a new ClientIDMode property on all ASP.NET controls which can be set either at the actual control or somewhere up the NamingContainer chain. If the ClientIDMode property is not set on a control it inherits the setting from the nearest NamingContainer with the exception of  the <asp:Content> placeholder which doesn’t participate in ClientIDMode processing (bummer!).



This means if you choose to you can set ClientIDMode on the Page level and it will trickle down into all the child controls on the page, but a custom naming container like a User Control can still override the ClientIDMode to enforce it’s naming container requirements. It’ll be interesting to see how much existing code might break based on this inheritance scheme as custom controls may lose controls over their ClientID naming if the ClientIDMode property isn’t set explicitly.



Anyway let’s take a look at a very simple example and how the ClientIDMode property affects the ID rendering. Imagine you have a page that uses a master page and is set up like this:



<%@PageTitle=""Language="C#"MasterPageFile="~/Site.Master"AutoEventWireup="true" 
CodeBehind="WebForm2.aspx.cs"
Inherits="WebApplication1.WebForm2"
ClientIDMode="Predictable"
%>

<asp:ContentID="content"ContentPlaceHolderID="content"runat="server"ClientIDMode="Static" >
<asp:TextBox runat="server"ID="txtName"ClientIDMode="Static" />
</asp:Content>



Here’s what the various values for the txtName property can look like:



AutoID



This is the existing behavior in ASP.NET 1.x-3.x where full naming container munging takes place.



<input name="ctl00$content$txtName" type="text" id="ctl00_content_txtName" />



In Beta 2 this is the default value for the Page. According to the latest VS 2010 documentation however, the default behavior by release time will be Predictable.



Static

This option forces the control’s ClientID to use its ID value directly. No naming container naming at all is applied and you end up with clean client ids:



<inputname="ctl00$content$txtName"type="text"id="txtName" />



This option is what most of us want to use, but you have to be clear on that this can potentially cause conflicts with other control on the page. If there are several instances of the same naming container (several instances of the same user control for example) there can easily be a client ID naming conflict. It’s basically up to you to decide whether this is a problem or not.



Note that if you assign Static to a Databound control like a list child controls in templates do not get unique IDs either, so for list controls where you rely on unique Id for child controls you’ll probably want to use Predictable rather than Static. More on this a little later when I discuss ClientIDRowSuffix.



Predictable



The previous two values are pretty self-explanatory. Predictable however, requires some explanation. To me at least it's not in the least bit predictable :-}.

MSDN defines this enum value as follows:




This algorithm is used for controls that are in data-bound controls. The ClientID value is generated by concatenating the ClientID value of the parent naming container with the ID value of the control. If the control is a data-bound control that generates multiple rows, the value of the data field specified in the ClientIDRowSuffix property is added at the end. For the GridView control, multiple data fields can be specified. If the ClientIDRowSuffix property is blank, a sequential number is added at the end instead of a data-field value. Each segment is separated by an underscore character (_).




The key that makes this value a bit confusing is that it relies on the parent NamingContainer’s ClientID to build it’s own client ID value. Which effectively means that the value is not predictable at all but rather very tightly coupled to the parent naming container’s ClientIDMode setting.



For our simple textbox example, if the ClientIDMode property of the parent naming container (Page in this case) is set to “Predictable” you’ll get this:



<input name="ctl00$content$txtName" type="text" id="content_txtName" />



which gives a name that walk up to the currently active naming container (the MasterPage content container) and starts the name from there downward. Think of this as a semi unique name that’s guaranteed unique only for the naming container.

If on the other hand the Page is set to “AutoID” you get with Predicable on txtName:



<input name="ctl00$content$txtName" type="text" id="ctl00_content_txtName" />



The latter is effectively the same as if you specified AutoID in this scenario because it inherits the AutoID naming from the Page and Content control of the page.  But again – predictable behavior always depends on the parent naming container and how it generates its id so the ID may not always be exactly the same as the AutoID generated value because somewhere in the NamingContainer chain the ClientIDMode setting may be set to a different value. For example if you had another naming container in the middle that was set to Static you’d end up effectively with an ID that starts with the NamingContainers' ID rather than the whole ctl000_content munging.



The most common use however for Predictable will be for DataBound controls, which results in a each data bound item to get a unique ClientID.



Predictable is useful, but only if all naming containers down the chain use this setting. Otherwise you’re right back to the munged Ids that are pretty unpredictable.



Inherit



The final setting is Inherit which is the default for all controls except Page (AFAIK). This means that controls by default inherit the naming container’s ClientIDMode setting.



Inheritance


The explicit values are pretty obvious in what they do and when they are applied to individual controls. AutoID is classic behavior, Static is what we want in typical client centric apps, and Predictable is what you typically will want to use for list controls and anything that has possible naming conflicts.



Things get a little more tricky with inheritance of these settings. Specicfically the ClientIDMode property inherits from a NamingContainer down. Unlike most other ASP.NET hierarchy inheritance the ClientIDMode inheritance is based on the NamingContainer not on the Parent Container.



What this means is that if you set ClientIDMode="Static" on a Page or MasterPage all controls inherit that settings:



<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true"          CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2"           ClientIDMode="Static" %>



If you don’t set the ClientIDMode on any other controls the entire page will use Static. Any UserControls can override the setting but all controls will use this setting.



Now imagine I do:



<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" 
CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2"
ClientIDMode="Predictable" %>



and I’m running inside of a master page and I put in a block of controls like this:



 <asp:Panel runat="server"  ClientIDMode="Static">
This is a test:
<asp:TextBox runat="server" ID="txtName" />
<asp:Button ID="btnSubmit" runat="server" Text="Go" />
</asp:Panel>



Quick what should you see? Unfortunately not what I would have expected – although it’s true to what the documentation advertises. The block above renders into:



<div>
This is a test:
<input name="ctl00$content$txtName" type="text" id="content_txtName" />
<input type="submit" name="ctl00$content$btnSubmit" value="Go" id="content_btnSubmit" />
</div>



What’s happening here is that even though we specified Static naming on the Panel (which is not a NamingContainer) Predictable naming is used which runs up to the nearest naming container – in this case the Master Page Content control and using that as its base for the name. If I want those controls to render with clean ids I need to explicitly mark the controls to use Static:



<asp:Panel runat="server"  ClientIDMode="Static">
This is a test:
<asp:TextBox runat="server" ID="txtName" ClientIDMode="Static" />
<asp:Button ID="btnSubmit" runat="server" Text="Go" ClientIDMode="Static" />
</asp:Panel>



or by changing the Page’s ClientIDMode to Static:



<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" 
CodeBehind="WebForm2.aspx.cs" Inherits="WebApplication1.WebForm2" ClientIDMode="Static" %>



With either of those in place I now get:



<div id="Panel1">
This is a test:
<input name="ctl00$content$txtName" type="text" id="txtName" />
<input type="submit" name="ctl00$content$btnSubmit" value="Go" id="btnSubmit" />
</div>



Notice that when page level ClientIDMode="Static" the <div> tag now renders with an explicit ID which is rather inconsistent (it’s not there if I just have ClientIDMode=”Static” on the Panel alone).



Note that you unfortunately cannot use an <asp:Content> control and specify the ClientIDMode like this:



<asp:Content ID="content" ContentPlaceHolderID="content" runat="server" ClientIDMode="Static">



This has no effect  on the controls contained inside of the Content container which still inherit the ClientIDMode from Page in this case. This is really annoying because the Content container certainly is part of the naming container hierarchy that is reflected in the ClientIDName for Predictable and AutoId.



There’s a way around this by using:




  • Static on the List Control


  • Predictable on all of the Child controls



This looks like this:



<asp:GridView runat="server" ID="gvProducts" AutoGenerateColumns="false"
ClientIDMode="Static" ClientIDRowSuffix="id"
DataSourceID="xmlDataSource"
>
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" id="txtTitle" Text='<%# Eval("title") %>' ClientIDMode="Predictable"/>
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField>
<ItemTemplate>
<asp:Label runat="server" id="txtId" Text='<%# Eval("id") %>' ClientIDMode="Predictable" />
</ItemTemplate>
</asp:TemplateField>

</Columns>
</asp:GridView>



which results in:



<table cellspacing="0" rules="all" border="1" id="Table2" style="border-collapse:collapse;">
<tr>
<th scope="col">&nbsp;</th><th scope="col">&nbsp;</th>
</tr><tr>
<td>
<span id="txtTitle_32">West Wind West Wind Web Toolkit</span>
</td><td>
<span id="txtId_32">32</span>
</td>
</tr></table>



This does produce what I would consider a desirable result although I had hoped that using Static on the list control without any further formatting would have produced this result. Unfortunately the Predictable setting on each of the child controls is required to get the clean ids into the child controls.





ClientIDRowSuffix


Another feature of the ClientID improvements in ASP.NET 4.0 is the ClientIDRowSuffix which can be applied to DataBound/List controls. I used it above in the grid to have the enumerated client id of the child controls use the value of an Id field from the database as the enumeration value. This setting basically determines how ID values for template controls in databound controls are generated, but it requires that the ClientIDMode is set to Predictable. It produces:



id="txtTitle_32"



where the _32 in this case comes from the Id of the data source which is nice than only using sequentially numbered values in previous versions of ASP.NET which were often worthless in client situations. Using an actual data value that can be looked retrieved on the client and sent back on an Ajax callback makes these IDs much more useful.



Wouldn’t it be nice if Client Row Ids could be generated?



What would be even nicer is that the generated ‘rows’ of a data bound control could optionally generate ids. In most Ajax situations the row level ID is really what’s useful – selections of rows for deletion, editing and updating always require an ID even if there are no child controls, but ASP.NET doesn’t provide an easy mechanism for embedding row ids. It sure would be get output like this:



 <tr id="content_gvProducts_33">
...
</tr>



This can be done with code in a GridView (and other list controls) with ItemCreated events it’s quite a pain to do this. For example for the gridview I’m using with a simple XmlDataSource control I have to do this:



protected void gvProducts_RowCreated(object sender, GridViewRowEventArgs e)
{
object dataItem = e.Row.DataItem;

if (dataItem != null)
{
XPathNavigator nav = ((IXPathNavigable)dataItem).CreateNavigator();
if (nav != null)
e.Row.Attributes.Add("id", this.gvProducts.ID + "_" + nav.GetAttribute("id",""));
}
}



to produce output like this:



<tr id="gvProducts_33"> ... </tr> 



which is anything but intuitive for such a common scenario (although this IS a bit easier to grab the data if you use Entity list or DataTable binding).



Data List Controls and Static Produces Invalid HTML



One more note: Using Static on list controls with child controls and NOT using Predictable for child controls is problematic as it will generate static IDs for ALL template items:



<table cellspacing="0" rules="all" border="1" id="Table1" style="border-collapse:collapse;">
<tr>
<th scope="col">&nbsp;</th><th scope="col">&nbsp;</th>
</tr><tr>
<td>
<span id="txtTitle">West Wind West Wind Web Toolkit</span>
</td><td>
<span id="txtId">32</span>
</td>
</tr><tr>
<td>
<span id="txtTitle">West Wind West Wind Web Store</span>
</td><td>
<span id="txtId">33</span>
</td>
</tr>
</table>



This is invalid HTML since there are multiple controls with the same id attribute on the page which is clearly undesirable. To fix this remember to use Predictable on any of the child controls.



Or better yet stay away from server controls altogether in template columns – stick to plain HTML controls and use AJAX to update values to the server more interactively. :-}



How should we use ClientIDMode?


I suspect it’s going to take some time to figure out all the little nuances of the new ClientIDMode features. At the very least the Static option on individual controls allows you to explicitly force controls to use the name you want it to and that’s a win any way you look at it.



For now I think the following is what I want to use in typical page scenarios in my applications:




  • Add ClientIDMode="Static" to each Page  (or in web.config’s <pages> setting)


  • Add ClientIDMode="Predictable" explicitly to each List Control Children in Databound Template


  • Override explicitly to Predictable where naming conflicts are a problem and to AutoId for the extreme edge case


  • For Control Development leave at default behavior if possible (ie. Inherit from parent)


  • Override only when necessary and preferrably on individual subcontrols



Also for now I think it’s a good idea to EXPLICITLY specify a ClientIDMode on each page (or in your project) or explicitly declare the value in your web.config file:



<pages clientIDMode="Static" />



to ensure you get a predictable setting since the current Beta 2 implementation and the documentation are at odds of what the default value actually is.