How to clean ID's on HTML output for server control in ASP.NET

Problem:

If you have a server control like Label or Image with a long name ID attribute when it's render as html the attribute ID is render on HTML output. If you have a lot of this controls on a web page this can introduce an overhead.

Solution

The first solution is to remove the ID on control. Like this :

<asp:Label  runat="server" Text="Salvo" ></asp:Label>

It work...but you can't use designer with visual studio because visual studio don't know the name of your label.

Then...this is not a good solution .

The second solution is to set ID with nothing (or null for C# programmers) at PreRender stage. Like this :

<script runat="server">

    Protected Sub DeleteID(ByVal sender As Object, ByVal e As System.EventArgs)
        If TypeOf sender Is Label Then
            Dim l As Label = sender
            l.ID = Nothing
        End If
    End Sub
</script>

<asp:Label ID="MyLongIDLabelForName" runat="server" Text="Salvo" OnPreRender="DeleteID"></asp:Label>

This is a good solution. :-) 

 

 

3 Comments

Comments have been disabled for this content.