ASP.Net Tip – CSS Styles applied on Server Controls


In this decade of web development, there is beauty in the design and simplicity of CSS styles applied on HTML elements.  The ability to apply simple keywords over any element and change its graphical/textual properties is powerful and easy.  The code below gives an example of how CSS & Javascript events are so simple to apply

<span style="color:#DEDEDE;background-color:#FFEEDD"
onclick="load()" >Label</span>

At first glance, the ASP.Net controls that ship out of the box may seem a bit limiting when compared to normal HTML elements in a style/javascript context.  While typing in the properties of any control, you might notice there are no “style” properties or “onclick” properties to apply javascript to.  But rather there is a style collection that can only be used at code behind and not declaratively.  There is an Click event, but its for button clicks that post back to the server and not to be used for client side javascript.  So at first glance, it may seem that ASP.Net server controls are not up to the task so easily.

Whats really is misleading in ASP.Net is Visual Studio’s intellisense.  Intellisense does not show that any elements declared as properties in the server control be rendered to HTML.  In fact, any attributes that the server control does not recognize will get propagated to the HTML.  So its actually perfectly legal to do the following.

<asp:Label id="Label1" runat="server" text="label"
 style="color:#DEDEDE;background-color:#FFEEDD"
 onclick="load();" />

Below is the actual HTML that has been rendered.
test
As you can see, all of the CSS style attributes and the javascript onclick event all pass through to the HTML, even though the Visual Studio intellisense does not show it as an option.  And this beats doing the above example in the Page_Load event in code behind.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s