Salvo Davide Rapisarda

Italian developer thinks.

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. :-) 

 

 

Posted: Nov 09 2007, 11:08 AM by Blackat.NET | with 3 comment(s)
Filed under:

Comments

Eduardo Costa said:

Nice tip!

Regards,

Eduardo Costa.

# November 9, 2007 11:02 AM

Edmund said:

Nice, but then you can't do any AJAX (as there's no client side IDs)

Edmund

# November 9, 2007 1:34 PM

Pablo Durtmünder said:

Wow, nice solution. I did this to my web app and it works perfectly! Much faster then before. Here's the code:

<html>

<body>

  <img src="iLoled.jpg" />

</body>

</html>

# November 9, 2007 3:24 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)