Friday, July 3, 2009

Working with Modal Popup extender control.

This blog discusses about the ASP.NET AJAX ModalPopupExtender control. In this blog we will see how to use the ModalPopupExtender control, how to display/show/call the ASP.NET AJAX ModalPopupExtender control from javascript, showing/displaying/calling the modal popup from a hyper link control within the gridview control and finally some important javascript methods of the ASP.NET AJAX ModalPopupExtender control. So first lets see how to use the ModalPopupExtender control.

How to use the ASP.NET AJAX ModalPopupExtender control?

Drag and drop a ASP.NET button/LinkButton/ImageButton or any control to an aspx page. To add a ModalPopupExtender control, drag and drop the control from the toolbox or Select the any of the ASP.NET controls like (button/LinkButton/ImageButton or any other control) and click the button with a greater than symbol as shown below.

image

When you click the arrow you will get a menu with an “Add Extender” option as shown below.

image

Click the “Add Extender” menu option and select “ModalPopupExtender” from “Extender Wizard” popup. Once you have added the ModalPopupExtender control you need an ASP.NET panel control. This is because the ModalPopupExtender control will show the content of the Panel control as a popup. Add ASP.NET Panel control and the content which you want to display as popup into the ASP.NET Panel control. Sample code with all the above requirement is pasted below. Don’t forget to drag and drop the ScriptManager control to the page.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ModalPopup.aspx.cs" Inherits="ModalPopup" %> 
<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="cc1" %> 
<!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>Modal Popup Demo</title> 
    <style> 
    .backgroundColor 
    { 
        background-color:Gray;    
        filter:alpha(opacity=25); 
    } 
    </style> 
</head> 
<body> 
    <form id="form1" runat="server"> 
    <div> 
        <asp:ScriptManager ID="ScriptManager1" runat="server"> 
        </asp:ScriptManager>        
        <asp:Button ID="popupBtn" runat="server" Text="Click to see the modal popup." /> 
        <asp:Panel ID="Panel1" runat="server" Style="display: none; padding:10px; border:1px; border-style:solid;" BackColor="#FF9933" Width="400px"> 
            <h3 style="text-align: center;" id="header">Modal Popup</h3> 
            <p>This is a Modal Popup extender control. You are seeing this because you have clicked the hyperlink button.</p> 
            <p style="text-align: center;"><asp:Button ID="closeBtn" runat="server" Text="Close" /></p>        
        </asp:Panel> 
        <cc1:ModalPopupExtender ID="ModalPopupExtender" runat="server" 
            TargetControlID="popupBtn" 
            PopupControlID="Panel1"              
            OkControlID="closeBtn" 
            BackgroundCssClass="backgroundColor" 
            DropShadow="true" 
            PopupDragHandleControlID="header"/> 
    </div> 
    </form> 
</body> 
</html>

From the above code one can see I have a ScriptManager, an asp:Button control, an asp:Panel control, some contents inside the panel control and then we have the ModalPopupExtender control. Normally when you attach an ASP.NET panel control to a ModalPopupExtender control it will become invisible in the HTML rendered to the browser and if due to some reason if the panel control is being displayed in the page then just set the "Style" property' “display” attribute to “none” as in the above e.g. Now when you click the button you will see a popup as shown below.

image

Now lets see how to configure the ModalPopupExtender control. The configuration is pretty simple, you need to set some properties and and you will have your Modal popup. The properties are as follows

TargetControlID: This property is the one which tells, on click of which control the popup should be displayed. In our e.g. we have given the TargetControlID as our button control. You can assign the ID of any ASP.NET controls like LinkButton, ImageButton, HyperLink, DropDownList, CheckBox, RadioButton etc. Even you can give a label’ id as the TargetControlID.

PopupControlID: The ID of the control to be displayed as a modal popup. In our e.g. we have given ASP.NET panel control’ ID. You can give any ASP.NET control’ ID. If for e.g if you give the ID of a textbox then the textbox alone will be popped up. Its not compulsory that you should provide a ASP.NET panel control.

OkControlID: The ID of the control which should act as an Ok button. Clicking of this control will dismiss the popup.

BackgroundCssClass: The name of the CSS class which needs to be applied to the background of the popup. One thing to note here is that if you don’t provide a CSS class then the modal popup will not function like a modal dialog i.e. One will be able to interact with the controls in the back of the popup control, so its imperative to provide a valid CSS class name value to the BackgroundCssClass property. In the above e.g. we have defined a CSS class called “backgroundColor” in the header section of the aspx page. Please note in the CSS class definition we have applied “filter” property to make the background transparent.

DropShadow: Accepts a boolean value which specifies whether the popup should have shadow. True will give a shadow and false will disable the shadow.

PopupDragHandleControlID: The ID of the control clicking on which the ModalPopupExtender can be dragged. The control should be enclosed in the control specified using PopupControlID i.e. in our case inside the ASP.NET panel control. If a particular control ID is set as the PopupDragHandlerControlID then one can click on that control and drag the ModalPopupExtender control. In the above e.g. we have set the ID of the “h3” control as PopupDragHandleControlID, clicking which the popup can be dragged.

CancelControlID: If you want a button to behave as a Cancel button provide the ID of the button. This button will cancel the popup.

Drag: This property takes a boolean value which when set decides whether the popup control can have the drag feature. A value of true means the popup extender control can be dragged around the screen whereas false will disable the drag.

RepositionMode: This property accepts four values. They are “None”, “RepositionOnWindowResize”, “RepositionOnWindowResizeAndScroll” and “RepositionOnWindowScroll”. The default value is “RepositionOnWindowResizeAndScroll”. Explanation of each values is given below.

RepositionOnWindowResize: Will reposition the popup when the window is resized.

RepositionOnWindowScroll: Will reposition the popup when the scroll bar is moved.

RepositionOnWindowResizeAndScroll: Will reposition the popup when you resize or when you move the scroll bar. Its a combination of both “RepositionOnWindowResize” and “RepositionOnWindowScroll”.

None: The popup will not be tinkered with. It will be shown in its original position irrespective of window resizing or scroll bar being moved.

DynamicServicePath: Link to a webservice/aspx page from where data or content needs to be retrieved and displayed in the popup extender control.

DynamicServiceMethod: The method name from which content needs to be retrieved. The method can be a webservice method or a method in your code behind file of your aspx file. If you leave the “DynamicServicePath” empty and provide DynamicServiceMethod name then the system will try to ping the same page’ and try to find a method. We will see an e.g. with web service shortly.

DynamicContextKey: The string value which will be passed as the parameter to the method specified in DynamicServiceMethod. One thing to note here is that the parameter should be named contextKey in the webservice/code behind.

X: The X coordinates for the popup control.

Y: The Y coordinates for the popup control.

Showing the content of a webservice (asmx) method in a ModalPopupExtender control.

Showing the output of a web method of a web service in a ModalPopupExtender control is also pretty simple. First you need to have a web service, if you don’t have one its very easy to create one in Visual Studio. Create a web service and add a method the output of which you want to display in a ModalPopupExtender conrol. Below I have pasted the code of my webservice.

using System;
using System.Collections; 
using System.Linq; 
using System.Web; 
using System.Web.Services; 
using System.Web.Services.Protocols; 
using System.Xml.Linq; 
 
[WebService(Namespace = "http://tempuri.org/")] 
/*The below attribute is needed so that the webservice can process calls from ASP.NET AJAX controls. Without the below attribute one may get the following error. "Web Service call failed: 500"*/ 
[System.Web.Script.Services.ScriptService] 
public class Service : System.Web.Services.WebService 
{ 
    public Service () 
    { 
    } 
    /*Method which will be called by the ModalPopupExtender control.*/ 
    [WebMethod] 
    public string HelloWorld() 
    { 
        return "<b>Hello World</b><br/>"; 
    } 
}

The above webservice is pretty simple. It has only one web method and the most famous of them all, the “HelloWorld” method. The method returns a HTML formatted “Hello World” string.
One thing to note while writing a web service whose methods can be called by the ASP.NET Ajax controls is that you need to add the “[System.Web.Script.Services.ScriptService]” attribute. If the before mentioned attribute is not added then you may get the below web service error.

Web Service call failed: 500

The mark up for the ModalPopupExtender control to display the webservice’ web method output is pasted below.

<!--Web service content display demo-->
<asp:Panel ID="webServicePanel" runat="server" Width="300px" Height="300" BackColor="Azure"> 
    <asp:Label ID="webServiceContentLbl" runat="server" Text="Label"></asp:Label> 
    <asp:Button ID="clsBtn" runat="server" Text="Button" /> 
</asp:Panel> 
<asp:Button ID="webServiceCall" runat="server" Text="Click to see the output of a webservice in a popup." /> 
<cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" TargetControlID="webServiceCall" OkControlID="clsBtn" DynamicServicePath="Service.asmx" DynamicServiceMethod="HelloWorld"   DynamicControlID="webServiceContentLbl"  
  BackgroundCssClass="backgroundColor" PopupControlID="webServicePanel" DropShadow="true">        
</cc1:ModalPopupExtender>

The difference from our previous ModalPopupExtender control is that we have configured some extra properties related to webservice request. They are DynamicServicePath where we have given the url of the web service, DynamicServiceMethod takes the web method name and finally DynamicControlID takes the ID of the control in which the output of the web method should be displayed. We have given the ID of the label control inside the panel control as the DynamicControlID. The label control will display “Hello World” string in bold.
The ModalPopupExtender is capable of displaying the output from normal aspx pages as well. To display some content its not compulsory that you need to create a webservice. One can directly show the output of a method in a code behind file in a ModalPopupExtender. Lets see how to do that.
Displaying the content of a webpage (aspx) method in a ModalPopupExtender control.
Below is the code behind file content of the ASPX page. The code is pretty straight forward. It has a static method called HelloWorld which returns the same text as that of the webservice.


public partial class ModalPopup : System.Web.UI.Page
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
    } 
    /// <summary> 
    /// Page method which will be called by the modal popup extender control. 
    /// </summary> 
    /// <returns></returns> 
    [System.Web.Services.WebMethod(), System.Web.Script.Services.ScriptMethodAttribute()] 
    public static string HelloWorld() 
    { 
        return "<b>Hello World</b><br/>"; 
    } 
}

One thing to keep in mind when you declare a method in an aspx which needs to be accessed by the ModalPopupExtender control or any ASP.NET AJAX control is to apply the following attribute.
[System.Web.Services.WebMethod(), System.Web.Script.Services.ScriptMethodAttribute()]

In addition to the above method attributes one need to declare the method as a static method. If the method is not declared static then you may not be able to ping from the client side. In the case of web service the method need not be static. Some of the errors which you may face because of not declaring the method static or because of not applying the above attributes are listed below.

1. Web Service call failed: 12030
2. Web Service call failed: 500

If the above two errors popup you know what to do? First check whether the method attributes are applied and secondly see to it that the method is declared as static in the code behind.

Below is the mark up needed to display the content from a method in an aspx page.

<!--Web service content display demo-->
<asp:Panel ID="webServicePanel" runat="server" Width="300px" Height="300" BackColor="Azure"> 
    <asp:Label ID="outputContentLbl" runat="server" Text="Label"></asp:Label> 
    <asp:Button ID="clsBtn" runat="server" Text="Button" /> 
</asp:Panel> 
<asp:Button ID="webServiceCall" runat="server" Text="Click to see the output of a webservice in a popup." /> 
<cc1:ModalPopupExtender ID="ModalPopupExtender1"       runat="server"  DynamicServicePath="ModalPopup.aspx" 
    TargetControlID="webServiceCall"          OkControlID="clsBtn"          DynamicServiceMethod="HelloWorld"          DynamicControlID="outputContentLbl"          BackgroundCssClass="backgroundColor"          PopupControlID="webServicePanel" DropShadow="true">        
</cc1:ModalPopupExtender>

You can see in the above mark up everything is same except for the webservice related properties, highlighted in Maroon. DynamicServicePath is used to specify the url of the page. If left blank it will refer the same page. DynamicServiceMethod is the method name in the aspx/codebehind which will be pinged by the ModalPopupExtender to retrieve data. DynamicControlID is the ID of the control in which you would like to display the output of the method. DynamicControlID should have the ID of a control inside the ASP.NET Panel control in our case or any control inside whatever container control the user is making use for popup. Also if you have any argument then you can use DynamicContextKey to pass the string argument.
Hiding and Showing the ModalPopupExtender control using javascript
The above e.g. are quite straight forward and easy to implement. Unfortunately a developer’ life is not a bed of roses. There may arise a requirement where one has to call/show/hide the popup control using javascript. So lets see how to do exactly this. Below is the HTML markup.

<asp:Button ID="popupScriptBtn" runat="server" Text="Click to view the modal popup using javascript" OnClientClick=”javascript:showModalPopup();return false;” />
<asp:Button ID="popupBtn" runat="server" Text="Click to see the modal popup." /> 
<div ID="div1" runat="server" > 
    <asp:Panel ID="Panel1" runat="server" Style="display: none; padding:10px; border:1px; border-style:solid;" BackColor="#FF9933" Width="400px"> 
        <table id="Table1" style="background-color: #C0C0C0; width: 400px; height: 5px;"><tr><td><h3 style="text-align: center;" id="header">Modal Popup</h3></td></tr></table> 
        <p>This is a Modal Popup extender control. You are seeing this because you have clicked the hyperlink button.</p> 
        <p style="text-align: center;"><asp:Button ID="closeBtn" runat="server" Text="Close" /></p>        
    </asp:Panel> 
</div> 
<cc1:ModalPopupExtender ID="ModalPopupExtender" runat="server" TargetControlID="popupBtn" 
    PopupControlID="Panel1" OkControlID="closeBtn" 
    BackgroundCssClass="backgroundColor" 
    DropShadow="true" PopupDragHandleControlID="header" 
    CancelControlID="" Drag="true" RepositionMode="None" />

Above markup is pretty much same as the one we used at the beginning of the blog. The only difference being we have an extra ASP.NET button, clicking which we will show the ModalPopupExtender control with the help of javascript. In the above markup we have used the “OnClientClick” property to assign the javascript, showModalPopup, which needs to be called when the button is clicked. The javascript to show and hide the popup is pasted below.

<script type="text/javascript" language="javascript">
//Javascript function to hide the popup control. 
function closeModalPopup() 
{ 
    //Using the $find javascript method to retrieve the modal popup control. 
    var modalPopup = $find('<%=ModalPopupExtender.ClientID %>'); 
    if (modalPopup != null) 
    { 
        modalPopup.hide(); 
    } 
} 
//Javascript function to show the ModalPopupExtender control. 
function showModalPopup() 
{ 
    //Using the $find javascript method to retrieve the modal popup control. 
    var modalPopup = $find('<%=ModalPopupExtender.ClientID %>'); 
    if (modalPopup != null) 
    { 
        modalPopup.show(); 
    }    
} 
</script>

In the above javascript we have two functions. One to show the ModalPopupExtender control and another to hide the control. In both the function we are using $find shortcut method to retrieve the popup control. To know more about $find method please see this link. Once we have retrieved the modal popup control we are calling the show and hide methods of the control to show and hide the control respectively.
Using the modal popup control within a GridView control

There is nothing different here. In a grid if you want to link the ModalPopupExtender to a control inside the GridView you need to just convert the column into a template column and add the ModalPopupExtender control to the column and configure the necessary properties as discussed. Below is a sample code where I have added the ModalPopupExtender control in the header section as well in a column of GridView control.



<asp:GridView ID="backIssueGrid" runat="server" AutoGenerateColumns="False" 
            DataMember="issue" DataSourceID="backIssuesXML"> 
        <RowStyle BorderColor="Tan" BorderStyle="Solid" BorderWidth="1px" /> 
        <Columns> 
            <asp:TemplateField HeaderText="Back Issues" HeaderStyle-CssClass="headerText"> 
                <ItemTemplate> 
                    <asp:HyperLink ID="title" runat="server" 
                        Text='<%# XPath("@title") %>' CssClass="gridText" NavigateUrl='<%# XPath("url") %>'></asp:HyperLink> 
                    <asp:Panel ID="webServicePanel" runat="server" Width="300px" Height="300" BackColor="Azure"> 
                        <asp:Label ID="outputContentLbl" runat="server" Text="Label"></asp:Label> 
                        <asp:Button ID="clsBtn" runat="server" Text="Button" /> 
                    </asp:Panel> 
                    <cc1:ModalPopupExtender ID="ModalPopupExtender1" runat="server" DynamicServicePath="ModalPopup.aspx" 
                        TargetControlID="title" OkControlID="clsBtn" 
                        DynamicServiceMethod="HelloWorld" 
                        DynamicControlID="outputContentLbl"  
                        BackgroundCssClass="backgroundColor" PopupControlID="webServicePanel" 
                        DropShadow="true">        
                    </cc1:ModalPopupExtender> 
                </ItemTemplate> 
                <HeaderStyle CssClass="headerText"></HeaderStyle> 
                <ItemStyle BorderColor="Tan" BorderStyle="Solid" BorderWidth="1px" />                
            </asp:TemplateField> 
            <asp:TemplateField HeaderStyle-CssClass="headerText">                
                <ItemTemplate> 
                    <asp:TextBox ID="quantityTxt" Width="30" runat="server" Text='<%#XPath("@noOfCopies") %>' CssClass="gridText"></asp:TextBox> 
                </ItemTemplate> 
                <ItemStyle BorderColor="Tan" HorizontalAlign="Center" BorderStyle="Solid" BorderWidth="1px" /> 
                <HeaderStyle CssClass="headerText"></HeaderStyle> 
                <HeaderTemplate> 
                    <asp:ImageButton ID="ImageButton1" runat="server" ImageUrl="some.gif" />                    
                    <asp:Panel ID="webServicePanel2" runat="server" Width="300px" Height="300" BackColor="Azure"> 
                        <asp:Label ID="outputContentLbl1" runat="server" Text="Label"></asp:Label> 
                        <asp:Button ID="clsBtn" runat="server" Text="Button" /> 
                    </asp:Panel> 
                    <cc1:ModalPopupExtender ID="ModalPopupExtender2" runat="server" DynamicServicePath="ModalPopup.aspx" 
                        TargetControlID="ImageButton1" OkControlID="clsBtn" 
                        DynamicServiceMethod="HelloWorld" 
                        DynamicControlID="outputContentLbl1"  
                        BackgroundCssClass="backgroundColor" PopupControlID="webServicePanel2" 
                        DropShadow="true">        
                    </cc1:ModalPopupExtender> 
                </HeaderTemplate> 
            </asp:TemplateField> 
            <asp:TemplateField> 
                <ItemTemplate> 
                    <asp:Label ID="Label4" CssClass="gridText" runat="server" Text='<%# Add(XPath("@noOfCopies"), XPath("@price"))%>'></asp:Label> 
                </ItemTemplate> 
            </asp:TemplateField> 
            <asp:CommandField ShowSelectButton="True" ButtonType="Button" 
                SelectText="Remove" ControlStyle-CssClass="buttonText" > 
            <ControlStyle CssClass="buttonText"></ControlStyle> 
            <ItemStyle BorderColor="Tan" BorderStyle="Solid" BorderWidth="1px" /> 
            </asp:CommandField> 
        </Columns> 
        <EditRowStyle BorderStyle="Solid" /> 
    </asp:GridView>

In the above e.g. you can see the markups highlighted in green. In the first portion I have place a popup control in the “ItemTemplate” and hooked the ModalPopupExtender control to a hyperlink control. Pretty simple, isn’t it? In the second section I have put the popup control in the HeaderTemplate of the column and hooked it to a ImageButton. So when one clicks on the image button in the header he will see a popup. If you want you can add javascript “onmouseover” and “onmouseout” behavior to the image in the code behind by adding attributes to the ImageButton control.

In my case I had to show help text whenever the user clicks the header text so instead of adding ModalPopupExtender control to each and every HeaderTemplate what I did is added the ModalPopupExtender control somewhere in the aspx page and hooked it to a hidden control and on click of the header, used javascript to display the popup control. The reason why I took this approach is that if I put the ModalPoupExtender in each column’ header template, it will generate as many popup extenders as the number of columns. My popup control needs to display help text and these help text were retrieved from a method in the code behind/webservice. So I used a javascript function and passed parameters necessary to retrieve the help text. Also people who have similar kind of requirement where for e.g. you have a column and you need to show some help text or some detailed information based on some parameters you can also follow the same approach. The approach will reduce the amount of html being generated. With this approach I wanted to highlight the subtle feature of ModalPopupExtender control where one can hook up the control to a hidden control and use javascript to show the control. This method can be very useful for controls to which ModalPopupExtender cannot be attached. I think thats enough, lets see the code in action.

<asp:GridView ID="backIssueGrid" runat="server"
AutoGenerateColumns="False" DataMember="issue" 
DataSourceID="backIssuesXML"> 
        <RowStyle BorderColor="Tan" 
BorderStyle="Solid" BorderWidth="1px" /> 
        <Columns> 
            <asp:TemplateField 
HeaderStyle-CssClass="headerText"> 
                <HeaderTemplate> 
                    <asp:HyperLink ID="title" 
runat="server" Text="Name" CssClass="gridText" 
NavigateUrl='javascript:showModalPopup("helpOne" 
);'></asp:HyperLink> 
                </HeaderTemplate> 
                <ItemTemplate> 
                    <asp:HyperLink ID="title" 
runat="server" Text='<%# XPath("@title") %>' 
CssClass="gridText" NavigateUrl='<%# 
XPath("url") %>'></asp:HyperLink>                        </ItemTemplate> 
                <HeaderStyle 
CssClass="headerText"></HeaderStyle> 
                <ItemStyle BorderColor="Tan" 
BorderStyle="Solid" BorderWidth="1px" />                        </asp:TemplateField> 
            <asp:TemplateField 
HeaderStyle-CssClass="headerText">                       <ItemTemplate> 
                    <asp:TextBox 
ID="quantityTxt" Width="30" runat="server" 
Text='<%#XPath("@noOfCopies") %>' 
CssClass="gridText"></asp:TextBox> 
                </ItemTemplate> 
                <ItemStyle BorderColor="Tan" 
HorizontalAlign="Center" BorderStyle="Solid" 
BorderWidth="1px" /> 
               <HeaderStyle 
CssClass="headerText"></HeaderStyle> 
                <HeaderTemplate> 
                    <asp:HyperLink ID="title" 
runat="server" Text="Address" CssClass="gridText"                         NavigateUrl='javascript:showModalPopup("helpTwo" 
);'></asp:HyperLink>                                             </HeaderTemplate> 
            </asp:TemplateField>            
            <asp:CommandField 
ShowSelectButton="True" ButtonType="Button" 
SelectText="Remove" ControlStyle-CssClass="buttonText" > 
            <ControlStyle 
CssClass="buttonText"></ControlStyle> 
            <ItemStyle BorderColor="Tan" 
BorderStyle="Solid" BorderWidth="1px" /> 
            </asp:CommandField> 
        </Columns>        
</asp:GridView> 
<asp:XmlDataSource ID="backIssuesXML" 
runat="server" 
DataFile="~/Data/BackIssue.xml"></asp:XmlDataSou 
rce> 
<asp:HyperLink ID="title" runat="server" 
Style="display:none;"> </asp:HyperLink> 
        <asp:Panel ID="webServicePanel" 
runat="server" Width="300px" Height="300" 
BackColor="Azure"> 
            <asp:Label ID="outputContentLbl" 
runat="server" Text="Label"></asp:Label> 
            <asp:Button ID="clsBtn" 
runat="server" Text="Button" /> 
        </asp:Panel> 
<cc1:ModalPopupExtender ID="ModalPopupExtender1" 
runat="server" DynamicServicePath="ModalPopup.aspx" 
TargetControlID="title" OkControlID="clsBtn" 
DynamicServiceMethod="HelloWorld" 
DynamicControlID="outputContentLbl"  
BackgroundCssClass="backgroundColor" PopupControlID="webServicePanel" DropShadow="true">        
</cc1:ModalPopupExtender>

The above code has ASP.NET hyper link controls in the header template which calls a javascript function using its NavigateUrl property and passes a string value to the javascript function based on which the help text is retrieved. Also as you can see we have a ModalPopupExtender control outside of GridView. A javascript function is used to show the popup control when you click the hyper link controls inside the header template of the gridview. Also note the hyper link control outside the GridView which has its style set to “None” so that the control becomes invisible. The javascript which is executed on clicking the hyper link controls inside the GridView is pasted below.

//Javascript function to show the ModalPopupExtender control.
function showModalPopup(helpId) 
{ 
    var modalPopup = $find('<%=ModalPopupExtender1.ClientID %>'); 
    if (modalPopup != null) 
    { 
        modalPopup._DynamicContextKey = helpId; 
        modalPopup.show(); 
    }    
}

In the above javascript we are setting the “_DynamicContextKey” with the help of the method argument. The argument is passed by the hyper link controls in the header template of the GridView. DynamicContextKey are nothing but the string arguments to be passed to webservice/webpage method. So by varying the DynamicContextKey we can get different messages to be displayed in the ModalPopupExtender control.

The code behind method which is called by the ModalPopupExtender control is pasted below.

[System.Web.Services.WebMethod(), System.Web.Script.Services.ScriptMethodAttribute()]
    public static string HelloWorld(string contextKey) 
    { 
        return "<b>Hello World</b><br/>" + contextKey; 
    }

So that’ about working with ModalPopupExtender control. Below are some of the important javascript properties and methods of ModalPopupExtender control.

Method/PropertiesDescription
_DynamicControlID

Using this property you can set/retrieve the ID for the dynamic control i.e. the control which will show the output of the method being pinged by the modal popup extender control.

_DynamicContextKeyProperty to set/retrieve the string parameter for the function which will be called by the ModalPopupExtender control.
_DynamicServicePath

Property to set/retrieve the path for the webservice/webpage.

_DynamicServiceMethod

Property to set/retrieve the method which needs to be invoked or pinged to retrieve the output.

_PopupControlID

The property can be used to set/retrieve the ID of the control which will be shown as the popup. Normally it will be the ID of the ASP.NET panel control.

_PopupDragHandleControlID

The ID of the control clicking on which the popup control can be dragged.

_BackgroundCssClass

CSS class name for the background of the popup can be set/retrieved using this javascript property.

_DropShadow

Boolean value which can be set/retrieved to enable drop shadow. A value of “true” means drop shadow is enabled, false means it is disabled.

_Drag

Property to set/retrieve the drag facility. If you want to enable set it as true.

_OkControlID

This property can be used to set/retrieve the “Ok” button.

_CancelControlID

Property to set/retrieve the “Cancel” button id.

_OnOkScript

Property to set/retrieve the script which needs to fired when “Ok” button inside the popup is clicked.

_OnCancelScript

Property to set/retrieve the script which needs to fired when “Cancel” button inside the popup is clicked.

_xCoordinate

Property to set/retrieve the X coordinates of the popup control.

_yCoordinate

Property to set/retrieve the Y coordinates of the popup control.

_repositionMode

Property to set/retrieve the Reposition mode. Reposition mode has been discussed somewhere else in this document. The property accepts integer as its value. The various values and their corresponding reposition mode are as follows. 0 means “None”, 1 means “RepositionOnWindowResize”, 2 means “RepositionOnWindowScroll” and finally 3 means
“RepositionOnWindowResizeAndScroll”. Each of this mode is discussed above.

_id

One can set/retrieve the ID of the ModalPopupExtender control.

So that’ about our disussion on ModalPopupExtender control.


Try to know more,

Sandeep

86 comments:

  1. How would you pass multiple parameters to the web service?

    ReplyDelete
  2. Hi Gman,
    As of now the only way to pass multiple parameters is to concatenate it to the string argument i.e. "_DynamicContextKey" using some logic like comma separated or colon separated. Then in the server side you can split the arguments based on comma/colon. As far as I know there is no other way provided as of now.

    ReplyDelete
  3. Hi Sandy,

    COuld you help me ? I am trying to use the modal popup exterder with hyperlink control, but when I run my project, the hyperlink is disabled, without point cursor and no click event.

    Is is possible to use with hyperlink ? If necessary, I can send to you my code.

    thanks,
    Marcelo.

    ReplyDelete
    Replies
    1. I have one question : I have Modal popup extender but its not working when i used Hover tooltip on grid.

      Can u pls help me out for this.

      Thanks in advance

      Delete
  4. Hi Marcelo,

    Yes you can very well use hyperlink control. I have used modal popup with many hyperlink controls. So there may be some small glitch. It will be great if you could send me the code to my mail id. My mail id is sndppr@gmail.com

    ReplyDelete
  5. Hi Sandeep,

    I have an MPE spawned from another MPE in which the top MPE has a panel that contains dynamically created checkboxes from Javascript. The problem I'm having is that the checkboxes don't change their state from checked to unchecked or vice versa when clicked on, or if they do, it seems like they go from unchecked to checked to unchecked again that I don't see it. Any thoughts on why this might be happening? I can provide example code and further explanation if necessary. Thanks.

    ReplyDelete
  6. Yes please, send me across the code. That will help me to narrow down the issue.

    ReplyDelete
  7. Hi Sandeep..nice article..but i hv 1 problem.can u give me answer pls???
    i hv a panel pnlDTL..which hv 2-3 dropdownlists..i hv given this panel as popupcontrolid for extender.i want to fill these dropdowns when this panel opens.but dropdowns are not filled .can u pls help me??

    ReplyDelete
  8. Hi,
    By default if you have any ModalPopup and a panel assigned to it, then everything gets rendered to the browser in one go i.e. the panel and controls inside the panel are rendered to the browser. When you assign TargetControlID property of the ModalPopup control what the system does is it calls the ModalPopup' "show" javascript method to popup the modal window. So if you want the dropdowns to be loaded with data then in the Page_Load event of the page where you have placed the ModalPopup control load the data into the dropdown.

    If you don't want this then you have to make use of a dummy server side control like hyperlink, button etc as highlighted in the above blog. Then show the modal popup control using a button or some other control which can do a postback from the server and in the server event of the control load the data into the dropdown and then call the "Show" method of the modal popup.

    ReplyDelete
  9. Sandeep:
    Did you figure out why a checkbox doesn't work with the ModalPopup? I am having the same problem, I am not able to check/uncheck a checkbox when it is in a panel, the panel is the target of the ModalPopup.

    ReplyDelete
  10. Hi,
    Sorry for the delayed reply, was fully occupied with the final phase of my project delivery. Could you send the code where you have used the checkbox in a ModalPopup. As such there is no restriction that you cannot use checkboxes.

    ReplyDelete
  11. Hi sandeep,

    my name is Lily..i need your help..i wanna using hyperlink to my modul popup extender..actually in my page I have 2 funtion :

    1) user click on Add button then will popup modul extender (no problem)

    2) user click on ID at Grid using Hyperlink then will popup modul extender. which i'm having problem using hyperlink..can u help me??

    ReplyDelete
  12. Hi Lilysue,
    It will great if you could elaborate more on your problem. Also some code will be great. You can mail me your code to sndppr@gmail.com

    ReplyDelete
  13. hi, i m developing shaepoint web part. I have a link button, 1 panel and modalpopup. I want, when i click on linkbutton panel should open as modalpopup. screen other than popup should be disabled(user should not be able to interact with rest of the screen). i set backgroundcssclass property of modal to a class which i m defining in core.css(12 hive). Now when i click on linkbutton, panel appears but it appears below the linkbutton instead of centre. Also, css is getting applied to partial screen. i mean css is not applied to screen where controls(linkbutton n panel) are present. what could be the reason. i want whole screen to be disabled.am i putting css to wrong place? is it due to combination of ajax with sharepoint web part. plz help.

    ReplyDelete
  14. hai sandeep,
    Is it possible to access a single panel with multiple modalpopup extenter?

    ReplyDelete
  15. Hi,
    Regarding Sharepoint and AJAX, I have not worked on sharepoint. If you could send me you code I can take a look at it and try to find whether there is any prob with the code.

    ReplyDelete
  16. Hi,
    Yes it is possible to access a single panel with multiple ModalPopupExtender (MPE). But what purpose will this serve? Do you have any requirement?

    ReplyDelete
  17. Hi Sandeep:

    I am trying to use the mpe, but the BackgroundCssClass is not working. I have read that the presence of other elements in the page using the position: css can cause a problem. Do you have any ideas on that?

    Thanks,

    -Jason

    ReplyDelete
  18. Hi Jason,
    It will great if you could send me the code and css used. If you have used position: fixed in CSS then IE will not be able to understand it. There are hacks available to fix this.

    ReplyDelete
  19. awesome blog dude, its really helpful fo me thnx buddy

    ReplyDelete
  20. I need to display the content in aspx file into popup panel.
    Is it possible Sandeep?

    ReplyDelete
  21. Hi,
    Yes, you can display the content of another aspx page in a modal popup control. For this you need to use an IFrame inside the MPE control. IFrames are not not considered good for doing things, rather you can use user controls and use the user control inside the MPE. Hope this helps.

    ReplyDelete
  22. hi how can we solve the problems with modalpopup in IE6

    ReplyDelete
  23. I am using modalpopup but in IE6

    Background controls are visible how can we solve it

    ReplyDelete
  24. The IE6 prob was solved over mail and mail conversation is pasted below.
    Hi XYZ,

    This is a typical windowing control problem. I am not sure whether this only IE6 problem, this can happen in most of the browsers. One way is to set the Z-Index property of the panel control to some value of 10001 and if this doesn't solve then you can use an i-frame inside the panel and display the controls inside it.

    Please let me know the result.
    Regards,

    Sandeep.

    /**Reply from the blog reader*/
    We solved that problem by putting a dummy iframe
    and giving style as

    position: absolute;
    width: 700px;
    height: 380px;
    z-index: 10;

    and making that frame visible and invisible with that popup thus solved the problem:)

    ReplyDelete
  25. helo sandeep i read ur posting Lamda Expressions

    can u please tell me more about LINQ

    and how can we make it useful in asp.net

    ReplyDelete
  26. Hi Sameera,
    Sure. But what specific info you need regarding LINQ?

    ReplyDelete
  27. wow what a long post...!!

    ReplyDelete
  28. I have Question :i have modal popup extender that contains asp panel and asp panel contains user control.modal pop up extenders popup control id is asp panel but user controls page load not firing

    ReplyDelete
  29. Nice comprehensive and helpful article. It helped me a lot.
    Greetings from across the border :)

    ReplyDelete
  30. hello I am Munendra.and I am using pop up extender to open the login pop up but submit button event is not fire. tell me what i do.

    ReplyDelete
  31. Hi Munundra,
    Are you using javascript? If yes then check for any javascript errors. Also check whether the button' type is set to "submit". Please send across the code so that I can exactly pinpoint the problem.

    ReplyDelete
  32. HI I send my code so please check it. tell me what is problem. submit button event is not fire.button Id is "LoginButton".

    ReplyDelete
  33. Hi Munendra,
    I didn't get your code. Can you resend it to sndppr@gmail.com

    ReplyDelete
  34. Hello i resend code.can u get it.

    ReplyDelete
  35. Hi Sandeep,
    How do I set the OkControlId when there is a usercontrol inside the panel for the modal popup extender.

    ReplyDelete
  36. Hi there,
    There are two ways of doing this. One way is to expose your button in the user control as a property and in the code behind do something like this.
    this.ModalPopupExtender1.OkControlID = this.USERCONTROL_ID.OkButton.ClientID;
    Or you can try something like this.
    this.ModalPopupExtender1.OkControlID = this.Page.FindControl("USERCONTROL_ID").FindControl("OK_BUTTON_ID").ClientID;

    ReplyDelete
  37. Hi Sandeep,
    Thanks for the response. How to pass a value from a textbox in the Modal Popup Extender to a textbox in the parent page using javascript..


    Thanks,
    Dhiraj

    ReplyDelete
  38. Hi Dhiraj,
    You can use document.getElementById method to do that. E.g.
    document.getElementById("PARENT_PAGE_TEXTBOX_ID").value = "some value";

    ReplyDelete
  39. Hi Sandeep,
    My Name is JuanM,Could you please help me I am using a popup extender and i would like to know if is possible to pass a data from a page to another page?
    I appreciate any help!!!.

    ReplyDelete
  40. Hi Andrew,
    That' a very tricky question. Every language has it' pros and cons. Language preference also depends on one' own choice. I would suggest to use both ASP.NET and PHP and see which one you prefer. On a personal note, I prefer ASP.NET.

    ReplyDelete
  41. Hi JuanM,
    It is very much possible to pass data from one page to another. You can make use of query string parameters in URL. Also one can make use of session variables as well. Also you can make use of the PreviousPage property in the current page and retrieve values from the the previous page. You can refer this URL for info.
    http://msdn.microsoft.com/en-us/library/6c3yckfw.aspx

    ReplyDelete
  42. @Sandeep...

    Can you use both ASP and PHP? will there be no problem if for example. i use login.asp and it will redirect to index.php???

    ReplyDelete
  43. Hi Andrew,
    It' always tricky to use two technologies. How will tell PHP that the request has been validated? These kind challenges you will have to overcome when using two technologies. Why would you use two technologies in the first place? Stick with one and it will make your life easy. :)

    ReplyDelete
  44. you got a point there. i was just curious on how my friend did it. maybe its just a htaccess modification. by the way can i add you in google plus?

    ReplyDelete
  45. hope i could invite you in google plus so that we could share some ideas with database design. i have invited you. take care.

    ReplyDelete
  46. Hi Andrew,
    Your friend would have created an authentication ticket and added the same to an auth cookie. I had similar kind of requirement where I had to use a third party page for authentication in an ASP.NET application.
    But as far as possible I wouldn't go with more than one technology and that also when it is not from the same company.
    Yes, sure you can add me. I would love to learn from you and also share my experience with you.

    ReplyDelete
  47. Hi Sandeep,
    I appreciate You help with the Popup Extender information, I have another question, how I can to validate in order to don't duplicate record information when i fill in the text of the form in a table Ej; Id = 1, Name =hola, Id=2 name hola id=3 name = hola, etc.
    Thank...
    Juan Manuel

    ReplyDelete
  48. Hi Juan,
    You can set the name field in the database as unique. This will not allow the user to enter two values of the same type. Or you can fire a select query against the database and check whether the name already exists, if it is there then don't add the value.

    ReplyDelete
  49. hi am my name is remi. i have followed all the instructions above. but when i get it to the browser it just refuse to respond when the button is clicked. please i would appreciate your response soonest.
    am using vs 2008 and .net 3.5

    ReplyDelete
  50. Hi Remi,
    Have you checked whether there are any Javascript errors are there? Button click may not be firing b'coz of some Javascript error. Please send across the code so that I can narrow down to the real problem.

    ReplyDelete
  51. Hi I m Ashutosh and
    I have one question : I have Modal popup extender but its not working when i used Hover tooltip on grid.

    Can u pls help me out for this.

    Thanks in advance

    ReplyDelete
    Replies
    1. Hi Ashutosh,
      I don't think the hover tooltip has anything to do with ModalPopupExtender (MPE). Things which I think can go wrong would be that the MPE properties have not been set properly. Or there can be some javascript error in your aspx page which is preventing MPE from working. These are few guesses, to narrow down to the actual problem I would request you to send me the aspx page. Code will help me to find the actual problem.

      Delete
  52. Great article -- but I'm stuck with trying to do this: use the model extender to create a popup div sucking in an aspx and rendering the controls on the aspx. I tried this example, but it only shows what the ws method writes back. Is their anyway I can use the modelpopup to load in an aspx file and include the asp.net components on that page? It'll be a nightmare to handcode these components to the codebehind ws method. Thanks!

    ReplyDelete
    Replies
    1. Yes. Put an iframe inside the modal popup extender and assign the source as a the aspx page. Hope this helps. iframes are bad there are some exception where you can use them.

      Delete
  53. Thanks for the quick reply -- would the aspx page on the main window and the aspx page in the iframe share the same session information? Or would the request via iframe in the popup generate a new session? Thanks again!

    ReplyDelete
  54. Thanks again Sandeep. What I wound up doing was using a aspx page (default.aspx) which has a declaritive usercontrol (I called it dashboard.ascx) which has a aspnet menu into it, that when a menu item is clicked, a partial postback will occur having the menu click event dynamically load another usercontrol into an updatepanel on the default page that shows a gridview. To edit the gridview, on that same usercontrol, would have an add/edit form that would display using an MPE. The most challening part was getting events wired up properly, specifically, when a edit button was clicked in the gv in the usercontrol that was dynamically loaded by the menu within another usercontrol on the page, it seemed like the only the page/dashboard would get there events fired, but not the grid (gv_RowCommand) on the grid. I could do a delegate on the dashboard, but that would be ugly. I can post what I did on here later on once I get the files all cleaned up if that would help others. Thanks again!

    ReplyDelete
    Replies
    1. Hi there,
      That' great to hear that you were able to solve your problem. It will very much helpful for others if you could share your solution.

      Delete
  55. I like your page background image :)

    ReplyDelete
    Replies
    1. Thanks mate. I am big fan of Beer. So that' why the background. :)

      Delete
  56. Hi,

    This is a really great article.

    I am currently stuck with an error 401.

    I disabled all authentication settings in the web config and it still does not work.

    Any idea ?

    ReplyDelete
  57. Did you check your IIS? What type of authentication does it have? May be your IIS setting is screwing up things.

    ReplyDelete
  58. Great article, helped me alot.

    ReplyDelete
  59. Hi,
    I have some problem launching the modal popup from a grid view. I need a link or a button in una field of the gridview that pass a parameter to the web service and the the modal popuop is showed. But when i try to use a button i only get a refresh of the page and when i use a link nothing appen

    ReplyDelete
    Replies
    1. Hi Jacksons,
      By default the page will do a total postback of the page. To prevent this you need to write return a false in javascript. For your scenario since you are using a webservice I would suggest to make use of an Ajax request and make a call to the webservice.
      The second option would be to call the web service in the code behind and based on the return type, try invoking the modal popup from code behind by invoking the show method.

      Delete
  60. This comment has been removed by the author.

    ReplyDelete
  61. Hi Sandeep,
    In my case i want the modalpopup to show after if condition is satisfies in a gvdetails_ItemCommand where gvdetails is the gridview id. But i am getting an exception as below
    " the control btnShowPopup has already data control registered". can you please tell what is the error in my case?.

    ReplyDelete
  62. hi, i want to pop up panel on button click can u plz help me wid the code? m using this.ModalPopupExtender1.Show(); but it seems to be not working

    ReplyDelete
  63. very useful and deep article article containing everything about model pop up extender..I also have a blog http://webcodeexpert.blogspot.in/ for sharing these type of useful codes for the web programmers..i was searching for the modelpopup and found your article and impressed by it..thanks. keep it up

    ReplyDelete
  64. How do you get it to scroll with the page. Im using C#

    ReplyDelete
  65. Hi...
    Sandy
    I've created list item for menus in my project & within list item i've put the anchor tag .I want to create modal-popup-extender control clicking on the anchor tag.
    Please help me....

    ReplyDelete
  66. PopupControlExtender is popup in ajaxcontroltoolkit 3.0 but not in 3.5

    ReplyDelete
  67. hi ....i want to disable the drag property of modal popup extender on mouse over event of a button...can you please help me on this ?

    ReplyDelete
  68. Hi, I popup a ModalPopupExtender from a checkBox in my gridview. The ModalPopupExtender has a dropdownlist. I
    have dropdown Index_changed code as following
    protected void ddlSupplierIndex_Changed(object sender, EventArgs e)
    {
    using (GridViewRow row = (GridViewRow)((CheckBox)sender).Parent.Parent)
    {
    TextBox txtBox = row.FindControl("txtSupplier") as TextBox;
    txtBox.Visible = true;
    DropDownList ddlList = row.FindControl("ddlSupplier") as DropDownList;
    txtBox.Text = ddlList.SelectedItem.Value;
    }
    }

    I got errow as this
    Unable to case object of type System.Web.UI.WebControls.DropDownList to type System.Web.UI.WebControls.CheckBox
    Can you please help me on this? Thanks

    ReplyDelete
  69. ASP.Net DropDownList using Modal Popup Extender - Selected value getting lost (http://aspforums.net/Threads/783405/ASPNet-DropDownList-using-Modal-Popup-Extender---Selected-value-getting-lost/) please help, iam not sure how to resolve

    ReplyDelete
  70. Excellent article. Some of the stuff in here I've never understood before.
    Thank you.
    Ken.

    ReplyDelete
  71. It is really a great work and the way in which u r sharing the knowledge is excellent.Thanks for helping me to understand basic concepts. As a beginner in Dot Net programming your post help me a lot.Thanks for your informative article.
    dot net training in velachery | dot net training institute in velachery

    ReplyDelete
  72. Given so much information in it. its very useful .perfect explanation about Dot net framework.Thanks for your valuable information. dot net training in chennai | best dot net training in chennai

    ReplyDelete

Please provide your valuable comments.