Use a Custom ID with ASP.NET and VB

Friday, January 30, 2009

At work we develop in the ASP.NET framework (with VB), which is powerful but it has a lot of oddities - especially for me writing all the markup and CSS. My biggest gripe has been with the ID property of any element. You give it an ID, and then ASP all assign it a different one when it renders! For example, lets say I write the following code:

<asp:Panel runat="server" id="MyPanel">Hello</asp:Panel>

What actually gets rendered to the page may look something like this depending on how many Masterpages and controls its been nested inside of:

<div id="ctl00_ctl00__userMessage_uxUpnMessage_MyPanel">Hello</div>

Why the long ID Microsoft? I understand that sometimes ASP will need these unique ID's for forms and postbacks, but in reality for many things (especially things that only relate to page structure or style) you don't need this unique ID, you only need the ID you gave it! Today I was messing around with exactly how to do this and I came across a solution! Check out the VB code below:

Protected Overrides Sub OnPreRender(ByVal e As EventArgs)
	Me.MyPanel.ID = String.Empty
	Me.MyPanel.Attributes.Add("id", "MyPanel")
	MyBase.OnPreRender(e)
End Sub

So just put that as the last step of your VB code, and it renders the exact way it should now - with the ID you told it to have in the first place. It's a bit of a hack, or a way to trick ASP into doing what I want, but ti works great. I'm sure there's a better way to implement this, or perhaps even extend certain elements to have a RenderID="MyNewIDName" property that would set the ID property from the front end instead.

Anyway, that's my big discovery for today. Hope it can help someone else out who was as frustrated as I was.

Posted by Chris Barr on 01/30 at 11:08 AM
Filed under Web, Code, ASP
No comments yet...
Post a Comment