views:

269

answers:

2

I'm looking at adding master pages to an existing site but have found that once I do, the elements' IDs get prepended with a code (e.g. ctl00_MainPageContent_).

Unforunately, this breaks existing scripts on the page that use the original, unmodified element ID.

I realize that I can replace it with <%= Element.ClientID %> but it'd be awesome if I could disable this behavior altogether.

So, can I keep the original IDs?

+2  A: 

The question was already answered in the previous post: Remove MasterPage Generated ID

The solution overrides the Render Event with the following code:

Protected Overrides Sub Render(ByVal writer As System.Web.UI.HtmlTextWriter)
    Dim Html As New StringWriter()
    Dim Render As New HtmlTextWriter(Html)
    MyBase.Render(Render)
    writer.Write(Html.ToString().Replace("name=""ctl00$ContentBody$", _ 
                  "name=""").Replace("id=""ctl00_ContentBody_", "id="""))
End Sub
Jose Basilio
Interesting approach. Are there any performance considerations to catching the full page output like that? Or possible issues with changes to the naming convention in the future?
Michael Haren
The performance hit is negligible in this case. However, this should be considered a workaround and not a permanent solution, since you are getting around the way that Master Pages generate unique IDs. Nevertheless, one positive is that if the naming convention for Master Page elements changes in the future, you only have to make one change on the Render event.
Jose Basilio
Not sure if this is the way to go... Hardcoding is bad and if you rearrange the containers .. the logic breaks.
Ben
+2  A: 

You can override ClientID and UniqueID in the controls. This is from here, an article by Rick Strahl.

public override string UniqueID
{
    get
    {
        return this.ID;
    }
}

public override string ClientID
{   
    get
    {
        return this.ID;
    }
}
Phaedrus
That's an interesting idea, too, but I don't think it'll work for me as it has some serious limitations with post backs and I'm trying to limit the changes I'd need to make to the existing code base. Thanks!
Michael Haren