Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a class to an ASP.NET control?

Tags:

html

css

asp.net

I've been working on someone's project and noticed Visual Studio produces a message for each ASP tag that has a class attribute. For example:

Attribute 'class' is not a valid attribute of element 'TextBox'.

If I visit the website, it seems to work correctly. An example that produces the message looks like this:

<asp:TextBox class="makeInline loginItem" ID="UserName" runat="server"></asp:TextBox>

On the website it becomes this:

<input type="text" class="makeInline loginItem" id="Login1_UserName" name="Login1$UserName">

So it looks like the class attribute gets carried over to the HTML tag. Is this fine, or is there a better way to do this?

like image 929
asimes Avatar asked Jan 29 '13 20:01

asimes


People also ask

How do I add a class to ASPX?

If you want to add attributes, including the class, you need to set runat="server" on the tag.

How do you add a class in CS?

Add a New Class to the ApplicationChoose 'Add Class...' from the Project menu of Visual Studio or Microsoft C# Express Edition. You will be asked for a name for the new class. Type 'Vehicle' and click the Add button. A new class file is generated with the definition of the class already added.

Can CSS add a class to an element?

CSS classes can be added to any HTML element.

Can I add two class to a div?

HTML elements can belong to more than one class. To define multiple classes, separate the class names with a space, e.g. <div class="city main">. The element will be styled according to all the classes specified.


2 Answers

Server controls use CssClass instead of class (presumably to avoid ambiguity over the meaning of class).

So it looks like the class attribute gets carried over to the HTML tag. Is this fine or is there a better way to do this?

Unknown attributes will be carried over. But while it works in this case, use the attributes that the control expects whenever possible. ASP.Net will occasionally alter the markup to "correct" it. Example: valid HTML 5 input type attributes (e.g. type="number") were "corrected" when the control was rendered until a fix was released to correct the problem.

You can place a custom attribute (e.g. data-*) on a server tag without concern.

<asp:TextBox runat="server" ID="txtTest" data-foo="bar" />

This does not cause a validation error in Visual Studio 2012, and renders as expected.

like image 161
Tim M. Avatar answered Nov 12 '22 03:11

Tim M.


The correct attribute to use is CssClass it will also be converted to the HTML class attribute when the page is generated.

like image 21
Blachshma Avatar answered Nov 12 '22 05:11

Blachshma