Any way to prevent master pages from changing element IDs?
Asked Answered
F

3

7

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?

Fatigued answered 10/5, 2009 at 2:38 Comment(0)
Y
5

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
Yate answered 10/5, 2009 at 2:53 Comment(5)
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?Fatigued
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.Yate
Not sure if this is the way to go... Hardcoding is bad and if you rearrange the containers .. the logic breaks.Turbosupercharger
Beats me why MS didn't use another attribute instead of ID. Perhaps we'd have to set 2 ids, one for client-side, one for server-side, but it seems better to break validation than cause these problems. :/Vacuous
<system.web> <pages clientIDMode="Static"></pages> </system.web> #5494630Nucleoside
D
4

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;
    }
}
Duodenary answered 10/5, 2009 at 3:12 Comment(1)
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!Fatigued
B
3

This question is old as dirt, but the new way to do it is ClientIDMode="Static".

Bike answered 10/10, 2019 at 20:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.