Return value from Modal popup
Introduction
You know how in facebook , when you click Add as Friend, this popup appears

once you click Send Request, the Add as Friend changes to Friend Request Sent
without refreshing the page, how to do this is in .Net ?
Dissection
we'll place the popup in a User Control
User Control
A modal pop containing whatever bussines we want to handle.
For sake of demonstration, let the popup display a calendar, and return the Selected Date into the source pages's Textbox.
<%@ 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.
<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 have came across the following solutions:
- ASP Server-Side JavaScript-like Calendar PopUp
- 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 delegate
, and an event
based on that delegate.
public delegate void DateSelectedHandler(DateTime dtDateSelected);
public event DateSelectedHandler DateSelected;
Note how we gave the delegate an argument of same type as the value we want returned (Datetime).
Then, we created a new event, of same type as the delegate.
Now in Calendar1_SelectionChanged
event, lets call the event instance we just created.
if (DateSelected != null)
DateSelected(Calendar1.SelectedDate);
What we did is simply passing 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
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
<uc1:calendarcontrol ondateselected="OnDateSelected" runat="server" id="ucCalendar">
</uc1:calendarcontrol>
.cs
protected void OnDateSelected(DateTime dtDateSelected)
{
TextBox1.Text = dtDateSelected.ToShortDateString();
}
Source Page Code Behind
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 want your control to stay visible on postbacks.(when user changes months for example)
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 in then pass the end result.
With the help of delegates and events, we were able provide a nice solution to an old problem.
发表评论
HBwNCL Wow! Thank you! I always needed to write on my blog something like that. Can I take a fragment of your post to my site?
HOFWqY I truly appreciate this blog post.Thanks Again. Much obliged.
vH64iq Nice weblog here! Additionally your website a lot up very fast! What web host are you using? Can I am getting your associate hyperlink on your host? I wish my site loaded up as fast as yours lol
l3dpR4 It`s really useful! Looking through the Internet you can mostly observe watered down information, something like bla bla bla, but not here to my deep surprise. It makes me happy..!
gBDg5F Incredible points. Sound arguments. Keep up the good work.
Punk not dead
I'm doing a phd in chemistry
How much is a Second Class stamp?
Could you ask him to call me?
I'll send you a text
About a year
What qualifications have you got?
Hold the line, please
I want to make a withdrawal
I'm sorry, he's
Pleased to meet you
I've been made redundant
A pension scheme
A financial advisor
I'd like to tell you about a change of address
There's a three month trial period
Where are you calling from?
How would you like the money?
I'm on a course at the moment
Children with disabilities discount pharmacy capalaba opening hours Anzevino, whose group has protected 1,600 acres of land that can be seen from Olana, believes there are compromise solutions that could be negotiated. He said he was encouraged the Federal Communications Commission this month called for a review of the proposal under the National Historic Preservation Act.
Have you got a current driving licence? how much do ivf drugs cost in canada Barco said her team of 60 volunteers, eight staff members and six interns are logging extra hours and have postponed its annual dolphin count in order to keep up with the deaths. The program is funded by grants, donations and contracts, and she says it's short on time and money.
Other amount prescription drugs nicaragua Activision itself is funding the deal with $1.2 billion in cash and $4.75 billion by raising new debt, Chief Financial Officer Dennis Durkin told analysts. It will also establish a $250 million revolving credit facility, he added.
I'm doing a masters in law costco pharmacy issaquah COPENHAGEN/LONDON, Aug 8 (Reuters) - Chinese authoritieshave visited a site operated by Danish drugmaker Novo NordiskA/S, the world's biggest maker of insulin, in thelatest sign of a widening investigation into Western drugmakers.
A pension scheme discount coupons on prescription drugs They are company managers who are using the latest, in-vogue tools like drones. Closer to earth than satellites, drones are making their appearance on the very large estates, meaning that the vines can be observed at a distance after heavy rain or hail.
Have you got a current driving licence? best online pharmacy to buy oxycontin Despite the problems Brazil is facing, Dr Ribeiro said his country was becoming better at tackling its crime problems. But he added that justice was very slow, which could keep spreading a "culture of impunity".
Thanks for calling tim's discount drugs florence al Data centres consume enormous amounts of power to runcomputer equipment and keep it cool. The amount of heat givenoff and transferred to the environment through cooling and airconditioning is enough to create detectable heat islands andmicroclimates in the vicinity of some of the largest serverfarms.
I do some voluntary work pharmacy online uk modafinil The parent company of First Community Bank said John Mendezwill no longer serve as president and chief executive of thecompany. The company appointed William Stafford II to serve asinterim CEO, effective Aug. 31. First Community Bancshares alsoappointed Gary Mills to succeed Mendez as CEO of First CommunityBank and as president of the company.
Incorrect PIN how are prescription drugs paid for in canada It won't just happen by itself, however, said Rolls. He warned that SME leaders need to actively place a bigger priority on exporting and set aside some time to put a plan into action, otherwise it will never happen.
I live in London london drugs online printing Itâs been a rough few months for the Internal Revenue Service. In May, Americans were rocked by revelations that the tax collecting agency had unfairly targeted conservative groups for extra scrutiny when they applied for tax-exempt status.
Accountant supermarket manager online pharmacy with next day delivery "Previous research has suggested that responsible game operators can try to help gamers improve control over their own behaviour by following a strategy of combining good game design with effective gamers' care polices, and referral services.
real beauty page prescription drugs such as those prescribed for adhd are not considered controlled substances On Thursday, two transit unions issued a 72-hour strike notice. The nation’s fifth-largest rail system, BART carries passengers from the Bay Area’s eastern suburbs across the water, through the city and to San Francisco International Airport.
Could you tell me the number for ? priceline pharmacy hours of operation Both Minsk and Belarus would like to revive the salesalliance, which controlled two-fifths of the world market, butwith China on board as a shareholder it may become harder infuture to curb sales volumes to underpin contract prices.
Do you like it here? online pharmacy espana In a landslide vote, the planning committee for Westminster City Council gave British Land approval to knock down properties at 82-84 Piccadilly and develop four buildings that will house apartments, offices and the exclusive Kennel Club.
I like watching football
What qualifications have you got?
I'm happy very good site
I'm a partner in
I'm sorry, she's
What sort of music do you listen to?
What are the hours of work?
Do you have any exams coming up?
Have you got any qualifications?
I'd like to pay this in, please
A law firm
I enjoy travelling somehow taking old viagra symptomscialis fee online slender Fannie and Freddie's future is now the biggest remaining question hovering over U.S. housing policy. According to Isaac Boltansky of Compass Point, any actual legislative action isn't expected until 2017, but in the last few months, House and Senate lawmakers have introduced major reform bills. Each calls for a version of "winding down" Fannie and Freddie, replacing them with new structures to support the mortgage market. But they diverge sharply on the question of the government's role.