简体   繁体   中英

Why are all my elements being renamed when I use master pages?

I can't understand why this is at all useful. I've got a master page with a content holder called Main, and I've got a content page with a matching content tag. However, I've noticed that when the pages get put together, the ids of some of my elements are changed, or should I say perverted, like so:

<input value="fizz-buzz" name="ctl00$Main$options" type="radio" id="Main_foobar"/>

This is wreaking havok on my css. Please help.

This is to ensure that multiple IDs from different sources will always have a unique name.

In ASP.NET 4.0, you can set the ClientIDMode to static and controls won't be renamed.

This is the way things are in ASP.net (till 3.5). This is to avoid duplicate ids and names of controls added to different content place holders.

In ASP.net 4.0 you can control how the control Ids are generated.

When you need to customize the style of an ASP.net Control, always set its CssClass attribute and refer to it in your stylesheet, even if the control is meant to be unique. Class names never change.

If you are stuck on 3.5 and can't upgrade to 4.0, I just put a solution on codeplex that I've been using for years.

http://awesomeclientid.codeplex.com/

Only just uploaded it a few days ago but basically it serializes all the controls that you specify to a Json array on the HTML doc for use in JavaScript.

I wrote a quick block post about it here:

http://www.philliphaydon.com/2010/12/i-love-clean-client-ids-especially-with-net-2-0/

You can either register the HTTPModule, or instinciate and serialize the page on PreRenderComplete on a page-by-page basis, what you will end up with is a JavaScript block in your doc looking along the lines of:

<script type=”text/javascript”>
//<![CDATA[
var controls = {
"txtUserName": "ctl00_ContentPlaceHolder1_txtUserName",
"txtEmail": "ctl00_ContentPlaceHolder1_txtEmail",
"btnSubmit": "ctl00_ContentPlaceHolder1_btnSubmit"
};
//]]>
</script>

Then when you wrote your JavaScript you can do:

<script type=”text/javascript”>
//<![CDATA[
var element = document.getElementById(controls.btnSubmit);
//]]>
</script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM