Redirection from iframe in asp.net or javascript

In this tutorial we will learn how to perform redirection from IFrame in asp.net.
For example, I has a webpage that contains the form containing two textboxes and one asp:button. When click on button it redirects the user to another page but problem was that the next page was being opened inside the iframe rather than in parent window because the webpage that containing the form was also in iframe.

Solution 1
Here we using the server side onClick event of asp:button to redirecting user to another page and client side OnClientClick event to open new page in parent window. NewWindow() JavaScript code that we have written in the OnClientClick event of asp:button will take care that user must be redirected to next page within parent window rather than IFrame.

Code: (iFrame)

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Ashish Blog</title>
    <script type="text/javascript">
        function NewWindow() {
            document.forms[0].target = "_top";
        }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    Ashish&amp;amp;#39;s Blog<br />
        UserName:<asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
        <br />
        Password:<asp:TextBox ID="TextBox2" runat="server" ></asp:TextBox>
        <br />
        <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="NewWindow();" onclick="Button1_Click"  />
    </div>
    </form>
</body>
</html>
 protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }

Solution 2:

 protected void Button1_Click(object sender, EventArgs e)
    {
       
        ClientScript.RegisterStartupScript(this.GetType(), "redirect", "if(top!=self) {top.location.href = 'Default.aspx';}", true);  
    }

Note:- In case if this code is not working properly in IE9 then you have to give the absolute path of targeting webpage such as

 protected void Button1_Click(object sender, EventArgs e)
    {
       
        ClientScript.RegisterStartupScript(this.GetType(), "redirect", "if(top!=self) {top.location.href = 'http://ashishblog.com/Default.aspx';}", true);  
    }

4 responses to “Redirection from iframe in asp.net or javascript”

Leave a Reply to livraghi80