October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk4 min

How to Wrap an iframe in an ASP.NET Web Forms User Control

Build a reusable Web Forms iframe wrapper with an .ascx user control, configure its source declaratively or in code-behind, and handle URL validation and standalone hosting correctly.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To reuse an iframe in ASP.NET Web Forms, put a server-side <iframe runat="server"> in an .ascx user control, expose the attributes you need as public properties, then register and use that control inside a Web Forms page’s server form. An .ascx file is not a standalone page and should not be the iframe’s direct target.

Create the iframe user control

Add an .ascx file, such as IframeWrapper.ascx, and make the iframe a server control by adding runat="server". The title gives the embedded frame an accessible name; loading="lazy" asks the browser to defer loading when appropriate.

As an Amazon Associate I earn from qualifying purchases.

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="IframeWrapper.ascx.cs" Inherits="WebApp.Controls.IframeWrapper" %>
<iframe id="Frame" runat="server" title="Embedded content" loading="lazy"></iframe>

In the code-behind, expose only the settings consumers need. This example provides a source URL and dimensions:

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
using System;
using System.Web.UI;

namespace WebApp.Controls
{
    public partial class IframeWrapper : UserControl
    {
        public string Src
        {
            get => Frame.Attributes["src"] ?? String.Empty;
            set
            {
                if (String.IsNullOrWhiteSpace(value))
                    throw new ArgumentException("Src is required.", nameof(value));

                // Apply your application's URL allow-list or validation policy here.
                Frame.Attributes["src"] = ResolveUrl(value);
            }
        }

        public string FrameWidth
        {
            get => Frame.Attributes["width"] ?? String.Empty;
            set => Frame.Attributes["width"] = value;
        }

        public string FrameHeight
        {
            get => Frame.Attributes["height"] ?? String.Empty;
            set => Frame.Attributes["height"] = value;
        }
    }
}

The designer file should declare Frame using a server-control type compatible with the target framework. If a framework upgrade causes an iframe parser or field-type error, check the generated designer declaration against the framework and regenerate or correct it as needed; a documented .NET 4 versus 4.5 case involved different generated iframe server-control types.

Register and use the control on a page

Register the .ascx file with an @ Register directive, then add the control inside the page’s server form. Microsoft’s inclusion guidance uses TagPrefix, TagName, and Src, and recommends a relative path for flexibility.

<%@ Page Language="C#" %>
<%@ Register TagPrefix="uc" TagName="IframeWrapper" Src="~/Controls/IframeWrapper.ascx" %>
<form id="form1" runat="server">
    <uc:IframeWrapper ID="HelpFrame" runat="server"
        Src="~/Help/Embedded.aspx" FrameWidth="100%" FrameHeight="600" />
</form>

The control’s public properties can also be assigned in page code-behind instead of markup. Keep the server form in the consuming page, not in the reusable user control.

Set a dynamic iframe URL safely

For a URL chosen at runtime, validate it according to your application’s policy before assigning it to the control. For example, set it during Page_Load on the initial request:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
        HelpFrame.Src = ResolveAllowedEmbedUrl(Request.QueryString["page"]);
}

ResolveAllowedEmbedUrl represents application code that validates and returns an allowed destination; it is not a built-in Web Forms method. Treat a configurable URL as untrusted input: allow-list acceptable schemes and hosts, reject dangerous schemes such as javascript:, and apply the site’s content-security policy and framing rules. Microsoft warns that HtmlGenericControl can display user input that might include malicious client script, so assigning an attribute is not a substitute for URL validation.

For simple cases, code-behind can set the server iframe directly with Frame.Attributes["src"] = validatedUrl;. A public property keeps that detail behind the user control’s interface and makes declarative use possible.

Choose how to assign the source and configure the frame

Choice Use it when Trade-off
Declarative Src The target is fixed for the page instance, such as an embedded help page. Clear in markup; the URL is not selected dynamically at runtime.
Dynamic Src property The application selects a destination from validated state or input. Requires an explicit validation policy before assignment.
Direct Frame.Attributes["src"] Page code needs to change the raw iframe attribute directly. Couples the caller to the control’s internal iframe rather than its public interface.
Same-origin target The framed page belongs to the same origin and the application has a legitimate need to interact with it. Origin alignment can permit more parent-frame interaction, subject to browser security rules and application policy.
External target The iframe must display content hosted elsewhere. Cross-origin restrictions can prevent the parent page from reading the framed document or resizing it through DOM access.

Expose additional iframe options—such as sandbox, dimensions, or loading behavior—as properties only when callers need to configure them. Keep a meaningful title on the frame. For content whose height may vary, prefer a fixed or responsive container rather than assuming the parent can inspect and measure a cross-origin document.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Use an .aspx host page when another site needs to frame the content

An .ascx user control is a component, not an independently requestable page. Microsoft states that user controls cannot be called independently; they can only be called from the page or another user control that contains them. To expose the component in an iframe, create an .aspx host page, register the .ascx control inside that page, and set the iframe’s src to the host page URL—not to the .ascx path.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Convert an existing Web Forms page into a user control

When turning a page into a reusable .ascx file, Microsoft’s conversion guidance is to rename the file extension, remove the html, body, and form elements, and replace the @ Page directive with @ Control. The consuming page remains responsible for the server form.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.