RedirectParentPageFromInsideIframe

How to redirect parent page from inside iframe in asp.net

Spread the love

If you have used iframes, you must have realized that you can’t simply redirect the parent page by using Response.Redirect in the child page. When we use Response.Redirect on the inner page, which is called using iframe into the parent page, instead of redirecting the parent page to the target url, it opens the target url inside the iframe. We can easily resolve this issue, by using javascript for redirecting, which provides us with the option to redirect the parent page of the iframe, and following is the code to do the same:

outerpage.aspx

1
2
3
4
5
6
7
8
9
10
11
12
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="outerpage.aspx.cs" Inherits="outerpage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <iframe src="innerpage.aspx" />
    </form>
</body>
</html>

innerpage.aspx

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="innerpage.aspx.cs" Inherits="innerpage" %>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button ID="btnredirect_asp" Text="Asp.Net Redirect" OnClick="btnredirect_asp_Click" runat="server" />
        <asp:Button ID="btnredirect_js" Text="Javascript Redirect" OnClick="btnredirect_js_Click" runat="server" />
    </form>
</body>
</html>

innerpage.aspx.cs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
 
public partial class innerpage : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
 
    }
 
    protected void btnredirect_asp_Click(object sender,EventArgs e)
    {
        Response.Redirect("http://aspskills.com");
    }
 
    protected void btnredirect_js_Click(object sender, EventArgs e)
    {
        ClientScript.RegisterClientScriptBlock(GetType(), "script", "this.parent.location.href='http://www.aspskills.com';", true);
    }
}

As you can see, when you click “Asp.Net Redirect” button, it will open the target page inside the iframe. However, when you click “Javascript Redirect” button, it will redirect the parent page to the target page, which is exactly what we wanted to achieve.

RedirectParentPageFromInsideIframe


Leave a Reply

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