ASP.NET WebControl ClientID Bloat

by michael 8/11/2008 2:29:00 PM

When you have a large control hierarchy this can lead to very large rendered ClientIDs.

The following illustrates what is rendered when you have a label within a GridView row within a UserControl within a Repeater.

<span id="ctl00_ContentPlaceHolder1_SampleRepeaterWithDescriptiveName_ctl00_SampleWebUserControlWithDescriptiveName_GridViewWithDescriptiveName_ctl02_Label1WithDescriptiveName">Sue 1</span>

This can greatly effect the page size especially if the Repeater or GridView has a lot of rows.

One way to take care of this is to override the ClientID property of the control.  Just create a server control that inherits from the WebControl.  Override the ClientID and UniqueID properties.  Use a hashcode of the string instead of the string itself.

Imports System.Web.UI.WebControls
Public Class LabelExtended
    Inherits Label
    Public Overrides ReadOnly Property ClientID() As String
            Return MyBase.ClientID.GetHashCode
        End Get
    End Property
    Public Overrides ReadOnly Property UniqueID() As String
            Return MyBase.UniqueID.GetHashCode
        End Get
    End Property
End Class

The output using the extended label is much more reasonable.

<span id="-819157441">Sue 1</span>

This took a sample page from 381 KB to 138 KB.  You can download the sample here.

I have a slight concern that the hashcodes may not always be unique.  They probably will be unique in the string ranges that would be generated in this case.  It might be better to use the hashcode generators found in the cryptopgraphy namespace.

I would be interested if anyone else has a better solution for creating shorter ClientIDs.

Currently rated 2.9 by 16 people

  • Currently 2.875/5 Stars.
  • 1
  • 2
  • 3
  • 4
  • 5



Michael Johnson Michael Johnson
Developer and Technologist.

E-mail me Send mail


    Recent comments




    The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.

    © Copyright 2016

    Sign in