nikodaemus
nikodaemus

Reputation: 2128

How do I style an ASP.NET HTML server control by ID?

When I create an HTML server control in ASP.NET 4.5 with an ID and use CSS to style that ID, it fails. When I inspect the source of the ASPX page, it shows that ASP.NET has changed my control's ID. In this instance...

<div id="PasswordStatus" class="well well-sm" runat="server">
  Current
</div>

...becomes...

<div id="article_PasswordStatus" class="well well-sm">
  Current
</div>

Can I then reliably (and with best practices in mind) just create the CSS style for #article_PasswordStatus instead? Or should I create a one-use CSS class for it, something like...

<div id="PasswordStatus" class="well well-sm password-status">
  Current
</div>

Preferably, can I still somehow use the original ID I assigned?

Note: I do not want to convert this to a Web server control.

Upvotes: 0

Views: 1194

Answers (3)

Rick S
Rick S

Reputation: 6586

Add in the ClientIDMode="Static" option to ensure your client Ids do not change. Information can be found here.

<div id="PasswordStatus" class="well well-sm" runat="server" ClientIDMode="Static">
    Current
</div>

This option forces the control’s ClientID to use its ID value directly. No naming container naming at all is applied and you end up with clean client ids

Upvotes: 1

Claudio Redi
Claudio Redi

Reputation: 68400

Assuming .net 4 and greater, you can use ClientIDMode. Your HTML would be like this

<div id="PasswordStatus" class="well well-sm" runat="server" ClientIDMode="Static">
    Current
</div>

When using Static the ClientID value is set to the value of the ID property. If the control is a naming container, the control is used as the top of the hierarchy of naming containers for any controls that it contains.

Upvotes: 2

walther
walther

Reputation: 13600

It's usually a best practice to use classes for css styling instead of IDs. You can avoid problems like this, reuse your css and so on, so that would be the path I'd choose.

ID in asp.net (webforms) can be modified in various ways and I wouldn't rely on that personally.

Upvotes: 0

Related Questions