ASP.NET Control HTML Elements/Tags Programmatically

by aherrick 3. December 2008 06:34

I was working on a project and was looking for more control over the elements I was creating in the HTML.  More specifically, I had a MasterPage setup and I wanted all pages to have the same background image throughout the site.

Simple.  Add a runat=server to your markup.  See below. 

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

You now have control of this element from the code-behind.

To add a background image to the div, you could do something like this:

bgimg.Style[HtmlTextWriterStyle.BackgroundImage] = ResolveUrl("~/images/bodyback.jpg");

The only thing to realize is what your generated markup is.  Asp.Net will auto-generate this tag to prevent naming collisions.  Just look out for it if you are trying to style the element with CSS or call it using javascript.

<div id="ctl00_bgimg" style="background-image:url(/HRR/images/bodyback.jpg);">
</div>

Enjoy!

Tags: ,



Powered by BlogEngine.NET 1.5.0.7
Theme by Mads Kristensen
Tweaked by ajondeck.NET

About the author

Andrew Herrick
I am a full time developer for Blue Horseshoe Solutions based out of Carmel, Indiana. I enjoy learning new technology and hope to give back with some of the cool things I pick up along the way.  Check me out on Stack Overflow!


Categories

None

Recent comments

Comment RSS

Disclaimer

The opinions expressed herein are my own personal opinions and do not represent my employer's view in  anyway.

© Copyright 2008