Why ASP.NET Master Page Name Mangling is important? I did not know about it before I encounter some issue with JavaScript ID naming. I cannot run the JavaScript code due to wrong ID name.
For example, you create a button with ‘Button1′ as its ID. Its name will still be ‘Button1′ under normal HTML. However, its name changes if you use ASP.NET MasterPage. It will change to ‘ctl00$Button1′ from ‘Button1′. You can find that out when you see its source code using Internet Explorer / Firefox view source function.
You will have Content Place Holder when you use Master Page. Then you will get your Button1 name as ‘ctl00$ContentPlaceHolder1$Button1′ if your button is in that Content Place Holder. ctl00 is your MasterPage ID while ContentPlaceHolder1 is your Content Place Holder ID. Therefore, you need to use the correct ID when trying to run JavaScript code at your website.
You can change the Content Place Holder ID in properties window. However, we cannot do so on Master Page. You need to add a Page_Init() function for your Master Page in C#.
protected void Page_Init( object sender, EventArgs e )
{
// this must be done in Page_Init or the controls
// will still use “ctl00_xxx“, instead of “MasterPageID_xxx”
this.ID = “MasterPageID”;
}
You will get ‘MasterPageID$ContentPlaceHolder1$Button1′ as your button ID then.
Tags: ASP.NET, C#, javascript, MasterPage, name