Load document in iframe dynamically

Published 11/3/2005 by Henry in ASP.NET | C#
Tags: ,

Supose you need to show an xml, html or aspx document inside an ASP.NET page. So you actually want to embed another page or document inside the original page. You want to load a document in an iframe dynamically from the server-side.
What you really need is an iFrame server control. However an iFrame is an html control and it's properties are not directly available at the server side (in the codebehind). So we need a way to access the 'src' property of the iFrame directly. Inside the iFrame's tag in the html of the aspx page we set the 'runat' attribute with the 'server' value.

   1:  <iframe id ="MyIframe" runat ="server"> 
   2:  </iframe> 

In the aspx.cs (codebehind) file we declare a System.Web.UI.HtmlGenericControl and name it (the name does not have to be the same as in the html page, but I think it is good practice to do so).

   1:  protected System.Web.UI.HtmlControls.HtmlGenericControl MyIframe;

We create a method we can call in order to load a document in our iFrame by using the FindControl method of the System.Web.UI.Page and typecast it This way we can acces all properties of the HtmlControl through the Attributes property. The "MyIframe" referred in Find Control is the ID as declared in the ASPX Page.

   1:  private void LoadDocumentInIFrame(string url)
   2:  { 
   3:      HtmlControl MyIframe = (HtmlControl)this.FindControl("MyIframe"); 
   4:      MyIframe.Attributes["width"] = "100%"; 
   5:      MyIframe.Attributes["height"] = "400px"; 
   6:      MyIframe.Attributes["src"] = url; 
   7:  }
   8:   
   9:   
  10:  // Example that calls the method
  11:  LoadDocumentInIFrame("http://www.google.com")


This way we can load a document in an iframe dynamically from server-side.
With the FindControl() we can get a reference to the HtmlGenericControl object and access the properties of it. As you will understand this is not limited only to the iFrame, but can be used for more 'HTML' controls.

Henry Cordes
My thoughts exactly...

 


Comments (2) -

Murulimadhav | Reply

5/16/2010 1:46:58 PM #

Hi,

In my web pages this "Load document in iframe dynamically" is not working , may be i made some mistakes . Please guide me .
               Murulimadhav

5/17/2010 5:52:30 AM #

@Murulimadhav:
Hi, if you tell me how I can help you, I am happy to do so.
Make sure you use runat="server" in the  <iframe id ="MyIframe" runat ="server" /> tag.
Also declare the iframe in your 'codebehind': protected System.Web.UI.HtmlControls.HtmlGenericControl MyIframe;

Regards, Henry

Add comment




  Country flag
biuquote
  • Comment
  • Preview
Loading