Click here to Skip to main content
15,884,836 members
Articles / Web Development / ASP.NET

Returning a value from a modal popup

Rate me:
Please Sign up or sign in to vote.
4.81/5 (11 votes)
3 Mar 2011CPOL2 min read 91.9K   3.2K   42   22
How to return a value from a modal popup.

Introduction

You know how in Facebook when you click Add as Friend, this popup appears:

Image 1

Once you click Send Request, the Add as Friend changes to Friend Request Sent. Without refreshing the page, how can we do this is in .NET?

Dissection

We'll place the popup in a User Control.

User Control

This is a modal pop containing whatever business we want to handle. For the sake of demonstration, let the popup display a calendar and return the selected date into the source page's textbox.

Image 2

ASP.NET
<%@ Control Language="C#" 
     AutoEventWireup="true" CodeFile="CalendarControl.ascx.cs"
     Inherits="CalendarControl" %>
<%@ Register Assembly="AjaxControlToolkit" 
             Namespace="AjaxControlToolkit" TagPrefix="asp" %>
<link href="Styles/Control.css" rel="stylesheet" type="text/css" />
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
    <ContentTemplate>
        <asp:Panel ID="Panel1" runat="server" 
                   BackColor="White" Style="display: none">
            <asp:Calendar ID="Calendar1" runat="server" 
                OnSelectionChanged="Calendar1_SelectionChanged"
                OnVisibleMonthChanged="Calendar1_VisibleMonthChanged"></asp:Calendar>
            <asp:ImageButton ID="btnClose" runat="server" 
                ImageUrl="~/Images/fancy_close.png"
                class="fancybox-close" OnClick="btnCloseMsg_Click" />
        </asp:Panel>
        <asp:ModalPopupExtender ID="Panel1_ModalPopupExtender" 
            runat="server" BackgroundCssClass="overlay_style"
            DropShadow="true" DynamicServicePath="" 
            Enabled="True" PopupControlID="Panel1"
            TargetControlID="FakeButton">
        </asp:ModalPopupExtender>
        <asp:Button ID="FakeButton" runat="server" Style="display: none" />
    </ContentTemplate>
</asp:UpdatePanel>

Source Page

Just the textbox where we want our result to return to, and a button to display the popup.

SourcePage.jpg

ASP.NET
<head runat="server">
    <title>Test</title>
</head>
<body>
    <form runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:Button ID="btnGetDate" runat="server" 
                 Text="Get Date" OnClick="btnGetDate_Click" />
            <uc1:CalendarControl ID="ucCalendar" 
                 runat="server" OnDateSelected="OnDateSelected" />
        </ContentTemplate>
    </asp:UpdatePanel>
    </form>
</body>
</html>

Please note that the textbox is contained in an UpdatePanel.

Problem

The main issue is: how to make the calling page feel your custom control? I.e., our control is a calendar, we want the textbox in the source page to see the date we just selected.

I came across the following solutions:

  1. ASP Server-Side JavaScript-like Calendar Popup
  2. ASP.NET AJAX Control Toolkit ModalPopupExtender Control in Action

Both are good, but I wanted something simpler without the fuss of JavaScript or iFrames, so I decided to use a different approach.

Solution

The answer is Event Bubbling.

In Our User Control

We will need a <a href="http://msdn.microsoft.com/en-us/library/ms173171(v=vs.80).aspx">delegate</a>, and an <a href="http://msdn.microsoft.com/en-us/library/aa645739(v=vs.71).aspx">event</a> based on that delegate.

C#
public delegate void DateSelectedHandler(DateTime dtDateSelected);
public event DateSelectedHandler DateSelected;

Note how we gave the delegate an argument of the same type as the value we want returned (DateTime). Then, we create a new event of the same type as the delegate.

Now, in the Calendar1_SelectionChanged event, let's call the event instance we just created.

C#
if (DateSelected != null)
    DateSelected(Calendar1.SelectedDate);

What we did is simply pass the value to our custom public event. Now, this event is exposed to our source page. This is Event Bubbling, events are propagated up the hierarchy (remember, bubble sort?).

User Control Code Behind

C#
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class CalendarControl : System.Web.UI.UserControl
{
    public delegate void DateSelectedHandler(DateTime dtDateSelected);
    public event DateSelectedHandler DateSelected;

    #region Events
    protected void Calendar1_SelectionChanged(object sender, EventArgs e)
    {
        if (DateSelected != null)
            DateSelected(Calendar1.SelectedDate);
    }
    protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
    {
        this.Panel1_ModalPopupExtender.Show();
    }

    protected void btnCloseMsg_Click(object sender, ImageClickEventArgs e)
    {
        Panel1_ModalPopupExtender.Hide();
    }
    #endregion

    #region Methods
    public void Show()
    {
        this.Panel1_ModalPopupExtender.Show();
    }
    #endregion
}

Now all we have to do is exploit our custom made event.

In Our Source Page

.aspx
ASP.NET
<uc1:calendarcontrol ondateselected="OnDateSelected" 
         runat="server" id="ucCalendar">
</uc1:calendarcontrol>
.cs
C#
protected void OnDateSelected(DateTime dtDateSelected)
{
    TextBox1.Text = dtDateSelected.ToShortDateString();
}

Source Page Code Behind

C#
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test : System.Web.UI.Page
{
    #region Events
    protected void OnDateSelected(DateTime dtDateSelected)
    {
        TextBox1.Text = dtDateSelected.ToShortDateString();
    }
    protected void btnGetDate_Click(object sender, EventArgs e)
    {
        ucCalendar.Show();
    }
    #endregion
}

Final Tip

If you want your control to stay visible on postbacks (when the user changes months, for example):

C#
protected void Calendar1_VisibleMonthChanged(object sender, MonthChangedEventArgs e)
{
    this.Panel1_ModalPopupExtender.Show();
}

Conclusion

So that's it, build your user control, handle your business and validation, and then pass the end result. With the help of delegates and events, we were able provide a nice solution to an old problem.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
Egypt Egypt
Enthusiastic programmer/researcher, passionate to learn new technologies, interested in problem solving, data structures, algorithms, AI, machine learning and nlp.

Amateur guitarist/ keyboardist, squash player.

Comments and Discussions

 
QuestionUpdate Panel and the Delegates Pin
haduken0330-Jul-14 16:41
haduken0330-Jul-14 16:41 
Answersimple js/ajax caledar Pin
shanid36015-Jun-12 22:57
shanid36015-Jun-12 22:57 
GeneralRe: simple js/ajax caledar Pin
Omar Gameel Salem15-Jun-12 23:06
professionalOmar Gameel Salem15-Jun-12 23:06 
GeneralMy vote of 5 Pin
Manoj Kumar Choubey28-Mar-12 0:23
professionalManoj Kumar Choubey28-Mar-12 0:23 
GeneralMy vote of 5 Pin
OmarMahmoudSayed17-Oct-11 23:46
OmarMahmoudSayed17-Oct-11 23:46 
GeneralMy vote of 5 Pin
Raheel Afzal Khan24-Apr-11 5:39
Raheel Afzal Khan24-Apr-11 5:39 
GeneralMy vote of 4 Pin
Monjurul Habib2-Apr-11 10:42
professionalMonjurul Habib2-Apr-11 10:42 
GeneralMy vote of 5 Pin
Monjurul Habib3-Mar-11 6:59
professionalMonjurul Habib3-Mar-11 6:59 
GeneralMy vote of 5 Pin
Slacker0073-Mar-11 5:26
professionalSlacker0073-Mar-11 5:26 
GeneralRe: My vote of 5 Pin
Omar Gameel Salem3-Mar-11 5:39
professionalOmar Gameel Salem3-Mar-11 5:39 
GeneralDumb Question... Pin
kaschimer28-Feb-11 6:14
kaschimer28-Feb-11 6:14 
GeneralRe: Dumb Question... Pin
Omar Gameel Salem28-Feb-11 6:37
professionalOmar Gameel Salem28-Feb-11 6:37 
the calendar is merely an example for sake of demonstration
what if you want to show a gridview to add items from ?
what if you want to show a login control ?
GeneralRe: Dumb Question... Pin
JV999928-Feb-11 22:17
professionalJV999928-Feb-11 22:17 
GeneralRe: Dumb Question... Pin
Omar Gameel Salem1-Mar-11 2:58
professionalOmar Gameel Salem1-Mar-11 2:58 
GeneralRe: Dumb Question... Pin
JV99991-Mar-11 3:27
professionalJV99991-Mar-11 3:27 
GeneralMy vote of 3 Pin
Slacker00728-Feb-11 5:43
professionalSlacker00728-Feb-11 5:43 
GeneralRe: My vote of 3 Pin
Omar Gameel Salem28-Feb-11 6:39
professionalOmar Gameel Salem28-Feb-11 6:39 
GeneralRe: My vote of 3 Pin
Slacker00728-Feb-11 6:51
professionalSlacker00728-Feb-11 6:51 
GeneralRe: My vote of 3 Pin
Dave Kreskowiak3-Mar-11 3:57
mveDave Kreskowiak3-Mar-11 3:57 
GeneralRe: My vote of 3 Pin
SiteBuilder10-Mar-11 15:59
professionalSiteBuilder10-Mar-11 15:59 
GeneralRe: My vote of 3 Pin
Omar Gameel Salem10-Mar-11 21:49
professionalOmar Gameel Salem10-Mar-11 21:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.