Working with ModalPopup Ajax Control
 
Published: 14 Dec 2007
Abstract
In this article the author shows how to display a simple popup window to the user with the ModalPopup Extender available in the ASP.NET Ajax Toolkit. After giving a few example cases of when to use the ModalPopup, the author walks through how to use this AJAX Extender control using source code snippets and a source download.
by Electronic Screw
Feedback
Average Rating: 
Views (Total / Last 10 Days): 167904/ 109

Introduction

This article explains using the ModalPopup Extender available in the ASP.NET Ajax Toolkit. ModalPopup Extender comes in handy when you want to display information on the page modally. I have used it in a couple of sites to display:

1. Tip of the day information

2. Login dialog box (display the login box modally and prevent the user from accessing the links before he signs in to the system)

3. Displaying Master-Child info

In this article I will explain how to display master-child information (Country - Cities) using ModalPopup Extender. The countries list will be displayed in a grid, and selecting a country row in the grid will open a modalpopup with all the cities available with the country. This example is taken to explain the concept, but in real-time you will be doing something useful like displaying all the employees in a GridView, and clicking on an employee row will display the employee information like Contact Details, Salary Details, etc.

All the necessary files, database, stylesheet and images used in this article are available for download from the link provided at the end of the article.

Note: The solution provided with this application is developed using ASP.NET AjaxToolkit version 1.0.11119.0 for ASP.NET AJAX version 1.0 and .NET Framework 2.0

A working example of this functionality can be seen at http://bg.analysterp.com. Click on the property images in the first page and you will see the detailed information about the selected property in a ModalPopup dialog. Ignore any errors if found, as the site is still under development.

Displaying the Master information

Create a new ASP.NET AJAX-Enabled website. Using a TableAdapter (available in the source with this article), ObjectDataSource and a GridView we display all the countries available in the database. The ASP.NET source for this is given below.

Listing 1: ASP.NET code for displaying the Country information in a GridView

<%--Countries Display--%>
<asp:Label ID="lblCountries" runat="server" Text="Countries"
    SkinID="Heading"></asp:Label><br />
<asp:UpdatePanel ID="upCountries" runat="server" UpdateMode="Conditional">
    <ContentTemplate>
        <asp:GridView ID="GridView1" runat="server" 
            AutoGenerateColumns="False" DataKeyNames="Id"
            DataSourceID="ObjectDataSource1" 
            OnSelectedIndexChanging="GridView1_SelectedIndexChanging">
            <Columns>
                <asp:BoundField DataField="Name" HeaderText="Name" 
                   SortExpression="Name">   
                    <ItemStyle HorizontalAlign="Left" Width="80%" />
                    <HeaderStyle HorizontalAlign="Left" Width="80%" />
                </asp:BoundField>
                <asp:TemplateField>
                    <ItemStyle HorizontalAlign="Center" Width="20%" />
                    <HeaderStyle HorizontalAlign="Center" Width="20%" />                    
                    <ItemTemplate>
                        <asp:ImageButton ID="showCities" CommandName="Select" 
                           runat="server" ImageUrl="~/images/add_details.gif" />
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>                
    </ContentTemplate>
</asp:UpdatePanel>
<asp:ObjectDataSource ID="ObjectDataSource1" runat="server" 
    OldValuesParameterFormatString="original_{0}"
    SelectMethod="GetCountries" 
    TypeName="ModalPopupTableAdapters.CountriesTableAdapter">
</asp:ObjectDataSource>

In the GridView1 we have a templatefield with an ImageButton (ID "showCities"). To use this button to show the cities for the corresponding country row, we set the CommandName="Select" and use the OnSelectedIndexChanging event of the GridView1.

First we will look at the .aspx source that we need to add to display the Cities in ModalPopup.

Listing 2: ASP.NET code to display cities

<%--Cities Popup Display--%>
<asp:Button id="btnShowPopup" runat="server" style="display:none" />
<cc1:ModalPopupExtender ID="mdlPopup" runat="server" 
    TargetControlID="btnShowPopup" PopupControlID="pnlCities"
    CancelControlID="btnClose" 
    BackgroundCssClass="modalBackground"></cc1:ModalPopupExtender>
<asp:Panel ID="pnlCities" runat="server" style="display:none;" 
  SkinID="PopUpPanel">
    <asp:UpdatePanel ID="upCities" runat="server" UpdateMode="Conditional">
        <ContentTemplate>
            <asp:Label ID="lblCities" runat="server" Text="Cities" 
                SkinID="Heading"></asp:Label><br />
            <asp:GridView ID="GridView2" runat="server" 
              AutoGenerateColumns="False" DataKeyNames="Id" Width="50%">
                <Columns>
                    <asp:BoundField DataField="Name" HeaderText="Name" 
                        SortExpression="Name">
                        <ItemStyle HorizontalAlign="Left" />
                        <HeaderStyle HorizontalAlign="Left" />
                    </asp:BoundField>
                </Columns>
            </asp:GridView>
            <asp:ObjectDataSource ID="odsCities" runat="server" 
                OldValuesParameterFormatString="original_{0}"
                SelectMethod="GetCitiesByCountryId" 
                TypeName="ModalPopupTableAdapters.CitiesTableAdapter">
                <SelectParameters>
                    <asp:Parameter Name="countryId" Type="Int32" />
                </SelectParameters>
            </asp:ObjectDataSource>
        </ContentTemplate>
    </asp:UpdatePanel>            
    <div style="text-align: right; width: 100%; margin-top: 5px;">
        <asp:Button ID="btnClose" runat="server" Text="Close" Width="50px" />
    </div>
</asp:Panel>

In the above code, the first line of markup is a normal ASP.NET button control with display style set to "none." I will tell you why I hide this button after explaining the next mark up.

Listing 3

<cc1:ModalPopupExtender ID="mdlPopup" runat="server" 
    TargetControlID="btnShowPopup" PopupControlID="pnlCities" 
    CancelControlID="btnClose" 
    BackgroundCssClass="modalBackground"></cc1:ModalPopupExtender>

Note: Make sure you have added a reference to AjaxControlToolkit.dll in your project and registered it in you page with directive

Listing 4

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" 
TagPrefix="cc1" %>

In the ModalPopup extender control, the TargetControlID is the control which activates the ModalPopup. Since we want to activate the ModalPopup from the ImageButton button in the Countries GridView and cannot access the ClientID of the control at design time, I created a dummy button and set its display style to none. The code for showing the modal popup is in OnSelectedIndexChanging event of the GridView1 which will be explained later.

The PopupControlID is the control that we want to display as Popup. In the above markup, it is set to "pnlCities" which contains the GridView2 to display the Cities.   

The CancelControlID is the id of the control that will cancel the modal popup. Inside the panel we have an asp:Button with ID "btnClose" that will cancel the modal popup. (Try to find why I kept the "btnClose" outside the UpdatePanel "upCities").

BackgroundCssClass is the css style that will be applied to the background when the Modal Popup is displayed.

We have all the ASP.NET code, so now we need to write the OnSelectedIndexChanging event of the Countries GridView to show the Cities in ModalPopup.

Listing 5: Code for GridView SelectedIndexChanged

protected void GridView1_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
{
  int _countryId = Convert.ToInt32(GridView1.DataKeys[e.NewSelectedIndex].Value);
  odsCities.SelectParameters["countryId"].DefaultValue = _countryId.ToString();
  GridView2.DataSource = odsCities;
  GridView2.DataBind();
  upCities.Update();
  mdlPopup.Show();
}

In the above code, find the selected countryId through the datakeys at NewSelectedIndex and set it as parameter value to ObjectDataSource. After binding the grid, update the updatePanel upCities and show the modal popup. That is it. Run the application to see the action.

Downloads

Notes

(1) In order to run the sample application on SQL Server 2005 Developer Edition, you should attach the database file provided with the above ZIP file and change your web.config "connectionStrings" section accordingly.

(2) The following error message will be shown inside web.config file if you use Visual Studio 2005.

The 'requirePermission' attribute is not declared

In order to fix the error, you should install Visual Studio 2005 SP1. Alternatively, you can also resolve it by opening dotnetconfig.xsd file located inside c:\Program Files\Microsoft Visual Studio 8\XML\Schemas\ folder and giving the following declaration around line 40 - 50.

<xs:attribute name="requirePermission" type="boolean_Type" use="optional" />
Conclusion

In this article you have seen the usage of ModalPopup Extender control available in the ASP.NET Ajax Toolkit.



User Comments

Title: sagar   
Name: sen
Date: 11/26/2012 7:13:48 AM
Comment:
hi
how r you
Title: aaaa   
Name: b
Date: 11/22/2012 10:23:27 PM
Comment:
aaaaa
Title: rtert   
Name: rtertret
Date: 10/25/2012 7:48:42 AM
Comment:
ertretertert
Title: gsg   
Name: gsfgs
Date: 10/16/2012 7:22:35 AM
Comment:
sdgfgs
Title: asdf   
Name: asdf
Date: 10/11/2012 3:21:02 PM
Comment:
asdf
Title: test   
Name: tester
Date: 9/20/2012 8:22:07 AM
Comment:
hjchj hjkhj jhvuf jkfb hklglhb lgkop
Title: test   
Name: test
Date: 7/18/2012 11:31:36 AM
Comment:
test
Title: gh   
Name: ch
Date: 6/14/2012 6:04:58 AM
Comment:
ccg
Title: test   
Name: test
Date: 5/19/2012 6:17:40 AM
Comment:
hi
Title: er   
Name: er
Date: 5/8/2012 3:16:54 AM
Comment:
er
Title: wwww   
Name: wwww
Date: 4/29/2012 6:48:46 PM
Comment:
wwwwwwwwwwwwwwwwwwwwwwww
Title: sending message   
Name: kiran
Date: 4/16/2012 12:41:18 AM
Comment:
hello world!
Title: Link don't works   
Name: José Mª Fueyo
Date: 3/14/2011 2:25:11 PM
Comment:
Hi
The link you put as sample (http://bg.analysterp.com) don't runs. Gives an IIS error (HTTP Error 403.6 - Forbidden)

Thanks,
Title: mr   
Name: david gray
Date: 2/8/2011 4:57:16 AM
Comment:
why not provide the solution file in the download so that it can be opened in vs?
Title: Hemangi   
Name: Francis
Date: 11/17/2010 1:44:10 PM
Comment:
Hemangi: You just need to create a button that show the popup in codebehind, just like this article, you can use a dummy button that is hiden in the page to associate with the ModelPopupExtender, and in your button you can show the pop up using MPE.Show(); this way you will be able to do the client checks, he will not call the event if you return false.
Title: az   
Name: ampatuan
Date: 10/25/2010 2:45:09 AM
Comment:
nice
Title: Bug   
Name: J Domit
Date: 6/26/2010 9:27:53 AM
Comment:
Yes this is very very tricky!
All depends on versions and releases. After hours and houurs I found something like: Use the ToolKitScriptManager instead of ScriptMangar...
Later on I've found, "ok, this sample works best on framework 2.0 and ajax 1,xyz".
Conclusion: GO TO HELL ASPIRATORS!!!
Title: Bug   
Name: Miguel Altamirano M
Date: 5/10/2010 3:57:55 PM
Comment:
All information I have read about modalpopup extender says that it works in modal mode. I understand this (if my poor english is enough to) as the other controls in the page remains inactive while the popup is displayed. But in my Web App it´s not doing this !!. The other buttons do what they have to do if I clik them. Why ??. How can I achieve this ?.
Title: one question   
Name: Hemangi
Date: 1/18/2010 6:58:31 AM
Comment:
If i want to perform some client side checks before i display the modal popup, how can this be controlled?

Currently i have a JS function called in the OnClientClick of the targetcontrolid (read button), the chekc is performed but the modal popup is displayed even if the check fails.
Let know if there is a way to control this.
Title: model popup   
Name: ram
Date: 12/26/2009 8:46:49 AM
Comment:
iam using popupextender and button also when iclick the button popup window open and no of buttons placed in the popupextender pls provide the solution
Title: Thanks a lot   
Name: bijeesh
Date: 12/17/2009 6:54:53 AM
Comment:
thanks for the article.
Title: ModelPopupextender   
Name: Karthik
Date: 11/4/2009 6:40:22 AM
Comment:
Hi,
The modelpopupextender article is good.I have a problem with modal popup extender.When the popup opens,the vertical scroll bar is not displaying.please provide the solution.
Title: ModelPopupextender   
Name: sangeetha
Date: 10/23/2009 5:35:51 AM
Comment:
Hai,,
I read the modelpopupextender article. This article is more helpful to me but u mension some of the css class like "modelbackground" this code is not added in this page ..if it is present it is more helpful to create modelpopup extender window

thankyou
Title: the link not working   
Name: Mann madhan
Date: 8/9/2009 3:51:01 AM
Comment:
the link http://bg.analysterp.com is not working for me. it shows sql error...
Title: Very Nice   
Name: Fayazoddin
Date: 7/16/2009 9:12:33 AM
Comment:
This Article is really very Nice.
Title: Not able to download   
Name: Meenakshi
Date: 6/11/2009 1:21:09 AM
Comment:
Article is nice...but I m not able to download the codes...can somebody help me out :(
Title: Nice!   
Name: H Nasir
Date: 4/15/2009 8:14:04 AM
Comment:
Very good explanation. keep going on
Title: He stole this code from MattBerseth.com   
Name: Jeff
Date: 3/6/2009 4:01:21 PM
Comment:
Dude, at least give Matt the credit. I have this same code in my example and it came from MATTBERSETH.com. Matt is brilliant, you are practicing plagerism.
Title: ModalPopupExtender   
Name: ashritz
Date: 2/20/2009 5:26:40 AM
Comment:
Hello
This Artical is really good.
But I have some query, Please help me.

I have a datalist in which I have a literal control,In that literal control I have binded products and their images,I want to open a modal popup on the click of the images and their names for that I have to use a Ajax ModalPopUpExtender,But I am not able to do that.
Please help me with the answer for this.


Thank You in advance
Title: sample download not working   
Name: Preeti
Date: 2/4/2009 12:07:53 AM
Comment:
When I used downloaded sample it is showing error

Failed to generate a user instance of SQL Server due to a failure in copying database files. The connection will be closed.
Title: Very Good Exampl   
Name: baski
Date: 1/13/2009 2:00:56 PM
Comment:
Very good example.button close is kept outside the update panel,this event handles to hide the modalpopup, otherwise button close resides inside the update panel then it wont fire the event
Title: Very Good Example for ajax popup   
Name: Arun
Date: 12/26/2008 2:27:06 PM
Comment:
Its really a good job.I found its very useful implement in my current architecture.I found difficulties in tradionally way implenting in javascript in my current architecture with very less coding.its really helpful article for me.
Thanks a lot

~Arun
Title: Ignore previous post on asynch callbacks   
Name: Michael W
Date: 11/20/2008 7:24:34 PM
Comment:
Hi again,

Sorry, the page refresh issue was my fault - I had not put an update panel around the parent grid view. Having done so, it works beautifully. Thanks for a great tutorial that shows you just the right amount of code to get a solution working!
Title: Asynchronous callback?   
Name: Michael W
Date: 11/20/2008 8:52:34 AM
Comment:
Hi,

This works great, except that my whole page refreshes when the popup gets populated with data. Is there a way round this? I want the popup to do an asynchronous call back, presumably, so that the whole page does not have to be refreshed when I click the link button in my grid view...
Title: 3   
Name: 3
Date: 8/9/2008 2:39:50 AM
Comment:
This article explains using the ModalPopup Extender available in the ASP.NET Ajax Toolkit. ModalPopup Extender comes in handy when you want to display information on the page modally. I have used it in a couple of sites to display:

1. Tip of the day information

2. Login dialog box (display the login box modally and prevent the user from accessing the links before he signs in to the system)

3. Displaying Master-Child info

In this article I will explain how to display master-child information (Country - Cities) using ModalPopup Extender. The countries list will be displayed in a grid, and selecting a country row in the grid will open a modalpopup with all the cities available with the country. This example is taken to explain the concept, but in real-time you will be doing something useful like displaying all the employees in a GridView, and clicking on an employee row will display the employee information like Contact Details, Salary Details, etc.

All the necessary files, database, stylesheet and images used in this article are available for download from the link provided at the end of the article.

Note: The solution provided with this application is developed using ASP.NET AjaxToolkit version 1.0.11119.0 for ASP.NET AJAX version 1.0 and .NET Framework 2.0

A working example of this functionality can be seen at http://bg.analysterp.com. Click on the property images in the first page and you will see the detailed information about the selected property in a ModalPopup dialog. Ignore any errors if found, as the site is still under development.
Title: Scroll bar goes down with no limit   
Name: JeffR
Date: 8/7/2008 2:41:42 PM
Comment:
I had the issue with the scrollbar growing to no limit and the dialog was not displaying correctly, it was showing up where it appeared in the page html and not centered in the browser. The solution I found was you must use the XHTML doctype with this. The older HTML Transitional doctype does not play well with it. We were using the older doctype on pages because it was better with IE6 when scrolling came into play but hopefully most of our clients are not on IE6 anymore.
Title: Scroll bar goes down with no limit   
Name: MikeF
Date: 7/23/2008 9:49:44 PM
Comment:
Looks like a lot of people have this problem. Someone must have a clue??????
HELP!
Title: Developer   
Name: Rahul Tiwari
Date: 4/30/2008 3:34:47 AM
Comment:
Master page Dosn't work
Title: Doesnt Work   
Name: Chetan Mulay
Date: 4/23/2008 9:07:06 AM
Comment:
The Code doesn't work.It gives a error as:This name contains Upper case Letters.
Title: Doesnt Work   
Name: Chetan Mulay
Date: 4/23/2008 9:05:40 AM
Comment:
\
\
\
\
\
\
\
\
\
Title: Sample & Download   
Name: Joe Stagner
Date: 4/16/2008 12:59:00 PM
Comment:
FYI - The download link appears to be broken and the authors on-line demo throws a SQL Server error.
Title: Master page doesn't work   
Name: Pranil
Date: 4/16/2008 12:19:22 PM
Comment:
I am also facing the same problem as Nelson. I have a master page with a treeview and four pages. On one of the pages i have a gridview where i need to popup an image on click of a column.
I tried implementing the way given here, but when the modalpopup is displayed, the page becomes large and can be scrolled down unendingly.

Any idea what is the problem?
Title: Developer   
Name: Tim
Date: 3/30/2008 4:47:50 PM
Comment:
I get a database erro when trying the the 1509_Working_with_ModalPopup_Ajax_Control example on http://bg.analysterp.com
Title: Master page doesn't work   
Name: Nelson
Date: 1/11/2008 2:15:28 PM
Comment:
I downloaded the code provided. I add a master page. I created a default2 page that used the master page. I created the events in the code behind. I ran the web application and go to the default2 page that I created. An error is received: Sys.ArgumentIndefinedException:Value cannot be undefined. Paramter name: type.
Can you reproduce this on your machine?I would like to know if the problem is my development environment or is something else. Thanks,
Nelson
Title: Master page doesn't work   
Name: Electronic Screw
Date: 1/9/2008 4:21:36 AM
Comment:
The working example I have provided (online) is infact done with MasterPage. If the page gets into a loop, a look into your code is needed.
Title: Master page doesn't work   
Name: Nelson
Date: 1/8/2008 10:43:09 AM
Comment:
I tried it with a Master Page scenario and it doesn't work. The page gets into a loop trying to do something and the scroll bar starts to go down with no limit. Do you have any idea why is this happening?






Community Advice: ASP | SQL | XML | Regular Expressions | Windows


©Copyright 1998-2014 ASPAlliance.com  |  Page Processed at 12/20/2014 8:07:46 PM  AspAlliance Recent Articles RSS Feed
About ASPAlliance | Newsgroups | Advertise | Authors | Email Lists | Feedback | Link To Us | Privacy | Search