Build dynamic IFrames in ASP.NET

Create the HtmlGenericControl object that will eventually render as an iframe and specify whatever attributes this iframe will have:

// Create new iframe control
HtmlGenericControl searchFrame = new HtmlGenericControl(“iframe”);
searchFrame.ID = “searchFrame”;
searchFrame.Attributes.Add(“class”, “searchFrame”);
searchFrame.Attributes.Add(“frameborder”, “0”);

Then, you can add it to the PlaceHolder’s controls collection:

// Add it to the Controls collection of the PlaceHolder control

Finally,  add the PlaceHolder control into ascx document where I’d like the iframe to eventually be:

<div class=”searchContainer”>
   <asp: PlaceHolder id=”searchHolder” runat=”server” />

Now, an iframe will appear in the outputted HTML code where the placeholder once was. But more than that, since was used an ASP.NET control to actually create the iframe, the iframe will be named uniquely. We even know what it’ll be called: this.UniqueID + “_searchFrame”. This is beneficial since you can now reference that iframe by name throughout  JavaScript code and show it or hide it when necessary.

If you are going to use this on a secure page (using https), you’ll have to set the src of the iframe to something on the site, otherwise you get a warning (at least in IE) telling you that the page contains secure and non-secure items. I’ve seen people create a blank HTML page in the site and set the src to that. I set the src = “javascript:;”. That takes care of the warning. If you have inherited your user control from either a User Control or a Web Control, you can implement the marker interface INamingContainer and multiple instances of your controls will have a unique name. I’m not certain if you can do that with a user control, but I can’t think of any logical reason why you couldn’t.



Leave a Reply

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

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

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s