adding runat=”server” changes the behaviour of the layout

I have a page with some controls, usercontrols etc.

when I change a div from plain <div id="foo"> to a <div id="foo" runat="server">
the layout complete changes.

why is that and how can I prevent it?

I’m using 2.0 .NET framework

Is it because .NET changes my id, which obviously I don’t want?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

If you’re targetting the ID of the div control in CSS and then running the control at server, you’ll find it no longer applies the style.

This is because ASP.NET has a built in mechanism (INamingContainer) to ensure than you don’t have multiple controls named the same. It does this by adding container prefixes so you end up with:

<div id="ctl00_ctl00_myDivName" runat="server" />

The easiest way around this is to change it from working on an ID to working on a class:

<div class="myDiv" runat="server"></div>

Alternatively, I believe that XHTML requires that Divs have closing tags so use

<div runat="server">Some content</div>

Method 2

When you add runat=”server” to a div, the system automatically generates the ID for it. It’s referred to as ID mangling. Unfortunately there isn’t much that you can do in the 2.0 framework for divs that I’m aware of (without it being a pain anyway), but in 4.0 we’re getting an override… On custom controls though (in 2.0) you can override the ClientID and UniqueID fields. So if you created a MyDiv class that used the div as a base and then created the ClientID/UniqueID fields you should be ok.

Your other option would be to update your CSS/javascript to use the mangled ID. It’s fairly static based on the position within the page as ASP.Net uses it to find a control during postback.

Method 3

Add ClientMode=”static” this will make sure your id is not changed to the clientside id for your control.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x