Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way of setting the src of an iframe from a codebehind file in ASP.NET?

I have an iframe that has a dynamic URL based on the results of web API call. What is the best way of setting its src in the aspx page? Here is an example of the iframe:

<iframe id="dynamicframe" runat="server"></iframe>

Should I set it directly in the codebehind like so:

dynamicframe.Attributes["src"] = "http://dynamicurl.com";

Or should I create a property in the codebehind and reference it in the iframe:

<iframe id="dynamicframe" src="<%= dynamicFrameUrl %>"></iframe>

Or some other method altogether?

like image 717
Daniel T. Avatar asked Oct 07 '22 15:10

Daniel T.


1 Answers

This is a general question that can stands the same for any html tag.

The alternative third option is to use a literal control and fully render the iframe on code behind as:

 txtLiteral.Text = "string.Format(
      "<iframe id=\"dynamicfrmae\" src=\"{0}\"></iframe>",   PageUrlForSrc  );

The different for all methods :

Direct write on page <%= %>

  1. Not work with update panel
  2. Its run the moment the page send to the browser (and not before on the page steps)
  3. Not accessible as control

This is the method that I avoid most. I use it only when I like to left some calculations for later and avoid page cycle, or when I have responce.flush() just before it.

Write it using to literal

  1. Compatible with UpdatePanel
  2. Not accessible as control

Write it as attribute on code behind

  1. Make the control pass the steps of the html cycle
  2. Is accessible else where on the page as variable
  3. The id of this control may change but you can avoid conflicts

All methods have their purpose, and I used then according what they fit best.

like image 56
Aristos Avatar answered Oct 19 '22 08:10

Aristos