Rick Strahl's Weblog  

Wind, waves, code and everything in between...
.NET • C# • Markdown • WPF • All Things Web
Contact   •   Articles   •   Products   •   Support   •   Advertise
Sponsored by:
West Wind WebSurge - Rest Client and Http Load Testing for Windows

ClientIDMode in ASP.NET 4.0


:P
On this page:

One of the more anticipated features of ASP.NET 4.0 – at least for me - 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.

It’s funny to think that such simple functionality should cause such complex workarounds and dependent behaviors but I suspect with a consistent regimen of CLientIDMode settings you can achieve output that works for any scenario. Time will tell.

Posted in ASP.NET  JavaScript  

The Voices of Reason


 

Steve
October 26, 2009

# re: ClientIDMode in ASP.NET 4.0

Funny... and still confusing.

The irony is, I just created a very complex web application in asp.net mvc and not once did I have to go through any of these hoops.

Sure, I had to create my own item ids in lists when I needed to - but ... that is how it is.

Is there an option you can just set in one place to tell the entire app you want to control the ids, period ?

DotNetKicks.com
October 26, 2009

# ClientIDMode in ASP.NET 4.0

You've been kicked (a good thing) - Trackback from DotNetKicks.com

Aaron Fischer
October 26, 2009

# re: ClientIDMode in ASP.NET 4.0

I am not sure we are really better off. I don't think we have escaped from id hell. At least we can fully control the ids on simple pages.

Rick Strahl
October 26, 2009

# re: ClientIDMode in ASP.NET 4.0

@Aaron - I definitely think this is an improvement. I think most people will be able to get away with running in Static mode and never have any problems. The biggest issue I suspect is going to be for control vendors who have logic that depends on specific client ids to be present and rely on them being unique.

For application level code though I think this is mostly a no-brainer. Set and forget.

Mark Kadlec
October 26, 2009

# re: ClientIDMode in ASP.NET 4.0

I had no idea this feature was part of 4.0, fantastic! I cringed with Master Pages before, no more.

Very timely post Rick, since you had a good workaround to the name mangling a few posts back.

Speednet
October 27, 2009

# re: ClientIDMode in ASP.NET 4.0

Fantastic writeup Rick, much appreciated. Surely to become a reference post. I have been waiting for this feature for years.

Unlike some others who are flipping out over the seemingly complicated options, in actuality they are exactly what we all need to customize the id property in any which way.

The only change I would have preferred is instead of using the ClientIDRowSuffix property (or maybe in addition to it), I wish they used a ClientIDFormat property (to specify the ID as a string with parts substituted like String.Format) or maybe to use a lambda function that would return a dynamically-created ID. (The latter would be awesome for data-bound controls.)

Rick Strahl
October 27, 2009

# re: ClientIDMode in ASP.NET 4.0

@SpeedNet - Yeah I think in practice for most folks it won't be complex. People that want this feature are likely to set the page to Static and be done with it. For me personally I can't think of many scenarios where I need to worry about ID conflicts since I don't use much in the way of complex nested controls.

I think where people might run into issues is with third party controls - there Static can really kill you especially on list controls since they won't generate unique Client IDs for children. That was a bozo move on part of the ASP.NET team IMHO. easy to fix with Predictable though.

Brendan Enrick
October 28, 2009

# re: ClientIDMode in ASP.NET 4.0

Awesome post! Yeah, I think a lot of us have been waiting a long time to be able to control those crazy auto-generated ClientIDs. Silly naming containers. They were a nice idea, but was a pain in the neck for the 90% case.

This will bring with it a lot of client side development. Should make for some really interactive ASP.NET sites.

Anuj Pandey
October 28, 2009

# re: ClientIDMode in ASP.NET 4.0

Very nice, this would mean my css would finally work for the simple controls like grid. and doesn't have to rely on .skin controls.

Andrei Rinea
October 29, 2009

# re: ClientIDMode in ASP.NET 4.0

This is another reason I will stick with ASP.NET MVC for all my future projects.

PimpThisBlog.com
October 29, 2009

# ClientIDMode in ASP.NET 4.0

Thank you for submitting this cool story - Trackback from PimpThisBlog.com

SKOROZSI.NET
November 04, 2009

# links for 2009-11-04

links for 2009-11-04

Tomas Matejka
November 08, 2009

# re: ClientIDMode in ASP.NET 4.0

This is perfect arcicle, but technology if still confusing.
It's easier to use $("[id$='_txtName']"); for element selecting in jQuery than clientIDMode. And you don't have to be afraid of javascript functionality when changing Page directives...

Rick Strahl
November 08, 2009

# re: ClientIDMode in ASP.NET 4.0

@Tomas - remember that using $("[id$='_txtName']") can be very slow so having clean IDs in the first place is a better choice.

Still think using Static on Page plus the occasional Predictable where uniqueness is required is pretty painless to work with. Time will tell.

manuel
November 10, 2009

# re: ClientIDMode in ASP.NET 4.0

#ctl00_content_txtName
{
font-weight: bold;
}

For all: please don't use this code in css!!!

Armcom
November 12, 2009

# re: ClientIDMode in ASP.NET 4.0

Personally until I actually get down and dirty with v4 I'm not which way I'd do it - However what I'm taking from this is at least the .NET team are listening to the community with the new releases.

Ryan Peterson
March 22, 2010

# re: ClientIDMode in ASP.NET 4.0

This can be used in Visual Studio 2010 without using the 4.0 framework.... Just an FYI to all those considering using this on an app developed in 3.5 framework.

Poul
April 16, 2010

# re: ClientIDMode in ASP.NET 4.0

I miss: ClientIDMode.None !
I often use server controls on the server only, for instance an <asp:label> to set text dynamically. However, the client will never need the ID, so it would be nice to not render it at all.
Also, for form elements the name is still those huge things. I would be be nice to shorten those too.
...and like you and others, I'm still confused, how to use it 'the right way', but it's definately a nice try.

My dotNet Adventures
April 19, 2010

# ClientIDMode in ASP.NET 4.0

ClientIDMode in ASP.NET 4.0

manningj
May 14, 2010

# re: ClientIDMode in ASP.NET 4.0

happen to have any idea on making it 'mostly static'? :)

my question only has 26 views so far and no real answers as of yet :(

http://stackoverflow.com/questions/2828719/asp-net-4-0-webforms-how-to-keep-contentplaceholder1-out-of-client-ids-in-a-s

Rick Strahl
May 14, 2010

# re: ClientIDMode in ASP.NET 4.0

You can set ClientIDMode on the Page or in the web.config file in the <Pages> section which wlil pretty much override everything. My approach has been to use web.config and only override with predictable for things like lists where the child clientID matters. Works well so far.

ASP.NET Web Forms bloggers
August 14, 2010

# What&rsquo;s New in ASP.NET 4.0 Part Two: WebForms and Visual Studio Enhancements

In the last installment I talked about the core changes in the ASP.NET runtime that I’ve been taking

Damian
November 18, 2010

# re: ClientIDMode in ASP.NET 4.0

Hi Rick,

Have you noticed that this property still doesnt let you set the item name that is added to the forms[] collection for a post! Proper annoying.

I had to add some extra functionality with the ajax toolkit some had to change from a html control to a server control and therefore i set the clientid to static to ensure i got the proper name added to the forms collection to retain my existing coding that picked up the form post.

Well...

if you let it use auto mangled then it sets the control ID to the random item, and the ID (mangled) gets passed into the forms collection.

if you set it to static it sets the controls name to the mangled value and the id to static but passes the mangled 'name' property into the forms collection! How annoying!

So it screws you which ever way you try and use. Therefore ive had to add the crappy mangled name into the code pulling the form value! Not good in my book.

Do you know of a way to control what it puts into the forms collection. I looked at adding it manually but the collection is read only.

Cheers

Rick Strahl
November 18, 2010

# re: ClientIDMode in ASP.NET 4.0

@Damian - yes. ClientIDMode only affects the ID not the NAME attribute on the control, so for post back form elements the name will still be a long name as held in UniqueID. This is reasonable though IMHO. If you really need simple names use plain INPUT elements rather than ASP.NET controls especially if you don't rely on POSTBACK assignment of controls anyway to retrieve the values by using Request.Form[].

zias
May 17, 2011

# re: ClientIDMode in ASP.NET 4.0

How can I get this to work for custom Server Controls that inherit from another control such as a Button?

At work, we have branded button controls, but for some reason ClientIdMode has not effect on it. I can't seem to find any information on how to fix this.

Any ideas?

Adam Edell
August 10, 2011

# re: ClientIDMode in ASP.NET 4.0

Call me old skool, but let's not throw out the baby with the bathwater!

//CASE A)
var myVal = $('#<%= textBox1.ClientID %>').val();

I prefer using the combination of server generated ClientID and javascript/jquery because I feel it's safer and preferable to typo prone, loosey-goosey scripting, like so:

//CASE B)
var myVal = $('#textBox1').val();

If any developer decides to change the name of textBox1 or remove it from the aspx page, you get a compile time error in CASE A and a runtime error only in CASE B.

I'll take the compile time error any day. Keep using server generated ClientIDs I say. They're better for you. I'll definitely use the row generating technique and may consider using static id's to save on HTML space, but I won't stop using .ClientID in javascript because it has saved me many times in looking for what otherwise would have been a typo and a runtime error.

Long live strongly typed compilers.

Adam :)

Rick Strahl
August 13, 2011

# re: ClientIDMode in ASP.NET 4.0

@Adam, yes that works, but there are problems with <%= %> tags in certain places (mainly nested controls and containers) inside of ASP.NET pages. Fragility of naming - how often do you really rename a control seriously? If it doesn't have a name and you used a default surely as soon as you use it in script or even server side code you're going to change it and give it a meaningful name. Renaming after the fact is an edge case at best, IMHO.

Adam Edell
January 05, 2012

# re: ClientIDMode in ASP.NET 4.0

@Rick, I love discussing this, first of all, and second, I agree! Renaming a control after the fact IS an edge case (something that DOES occur, but not too often) and the <%= syntax does fail in nested controls and templated containers. But removing a control is not an edge case - it happens frequently upon refactoring an area into a user control or new requirements for example. I'd say that CASE A (above) above has saved me countless hours of hunting down runtime javascript bugs because I avoided coding like CASE B. Thanks for the discussion!

Rae Benedetto
October 24, 2012

# re: ClientIDMode in ASP.NET 4.0

First off, I am not an ASP coder. I know next to nothing about this. I am Section 508 accessibility and remediation specialist. As you no doubt know, in order for an HTML form to be accessible to a screen reader form field name and for field id must match.

We have a vendor who tells me that fixing this is prohibitively expensive. This doesn't make sense to me and from what I see in your discussion, this may not be the case. Could it be just a matter of tweaking the code?

Here is a chunk of the final code we are getting... looks very similar to what you are talking about here. Can you explain in nonASP-expert language what is happening here and how difficult it should be to remedy ? Thank you.

<input name="ctl00$MainContent$chkAreasOfInterest_2" type="checkbox" id="MainContent_chkAreasOfInterest_2" /><label for='chkAreasOfInterest_2'>Mental health promotion</label>

Rick Strahl
October 24, 2012

# re: ClientIDMode in ASP.NET 4.0

@Rae - ClientIDMode allows fixing the ID attribute so that it's a simple value. The name attribute however is not affected by that.

I'm not really sure why the longer name would be a problem for accessibility however - while the id/name is ugly, it should hardly get in the way of accessibility or display of information about the control in any way.

Sunil
December 30, 2013

# re: ClientIDMode in ASP.NET 4.0

I just want to remove "ctl00$" form name, bucause jqueryui validation and form post works with name not id so is there any way to remove "ctl00$" from name attribute.

Mark
November 14, 2014

# re: ClientIDMode in ASP.NET 4.0

So I was playing around with this and found several odd things.

I put Static on my page and Predictable on the immediate child control and found that repeater/gridview controls behave a little oddly.

Say you have a GridView that repeats a number of rows with a number of child controls. You get
<tr id="...Foo_0">
<td><input type="hidden" id="...Foo_ChildId_0"></td>
...

So if you're looking at the ids and trying to infer relationships (in a more limited form) the child control doesn't cleanly match the parent.

Just bitchin', but it seems like Foo_0_ChildId would have been more intuitive behavior...

bardia
April 18, 2016

# re: ClientIDMode in ASP.NET 4.0

is there any solution to clean up 'name' property of control , like this "ctl00$content$txtName" to this "content" ?

Ishant Jindal
September 01, 2020

# re: ClientIDMode in ASP.NET 4.0

is there any solution to clean up 'name' property of control , like this "ctl00$content$txtName" to this "txtName" ?


Rick Strahl
September 01, 2020

# re: ClientIDMode in ASP.NET 4.0

@Ishant - nope. Only the id attribute is affected by this. ASP.NET needs the name to reflect the container hierarchy using that funky syntax in order to match server side controls to the POST data you send back. If you want just 'clean' naming, use a plain <input> control and explicitly read Request.Form["txtName"] - IOW, don't use the control model.


West Wind  © Rick Strahl, West Wind Technologies, 2005 - 2024