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?
If you want to add attributes, including the class, you need to set runat="server" on the tag.
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.
CSS classes can be added to any HTML element.
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.
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.
The correct attribute to use is CssClass
it will also be converted to the HTML class
attribute when the page is generated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With