Friday 19 February 2010

ASP.Net: Fetching data from a PopUp

Consider the case where you need to popup a page, perform some operation and fetch the resultant data from the Pop-Up page into your Parent page.
Starting with the Parent page, lets have a TextBox on the Parent page where we need to enter data from the Pop-Up page.Here is the code:

<head runat="server">
    <title>Parent Page</title>
    <script type="text/javascript" >
    function text()
    {
    window.open("popup.aspx", null, "scrollbars=no,menubar=no,status=no,width=400,top=300,left=350,right=0,height=250,resizable=no");
    }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
      <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="return text();" />
    </div>
    </form>
</body>


On clicking the button on the base page the other page pops up. Here we are selecting a value in the Dropdown list and the selected value is returned to the base page using the code in javascript. The magic code is "window.opener.document.getElementById....", through which the parent page access the value that it is seeking.

<head runat="server">
    <title>PopUp Page</title>
    <script language="javascript" type="text/javascript">
        function passValues()
        {
          var oOption = document.getElementById("DropDownList1");
          var strText = oOption.options[oOption.selectedIndex].text;
          window.opener.document.getElementById("TextBox1").value = strText;           
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <asp:DropDownList ID="DropDownList1" runat="server" AutoPostBack="True">
        <asp:ListItem>Bulgaria</asp:ListItem>
        <asp:ListItem>Belgium</asp:ListItem>
        <asp:ListItem>Slovenia</asp:ListItem>
        <asp:ListItem>Latvia</asp:ListItem>
        <asp:ListItem>Gibraltar</asp:ListItem>
      </asp:DropDownList>
      <input type="submit" onclick="passValues(); window.close()" value="Submit" />
    </div>
    </form>
</body>
</html>

The hardcoded data from the Dropdownlist can be replaced with necessary data and you will get the desired result.


No comments: