Positioning a ModalPopup (C#)
The ModalPopup control in the AJAX Control Toolkit offers a simple way to create a modal popup using client-side means. However the control does not offer a built-in functionality to position the popup.
Overview
The ModalPopup control in the AJAX Control Toolkit offers a simple way to create a modal popup using client-side means. However the control does not offer a built-in functionality to position the popup.
Steps
In order to activate the functionality of ASP.NET AJAX and the Control Toolkit, the ScriptManager
. control must be put anywhere on the page (but within the <form>
element):
[!code-aspxMain]
1: <asp:ScriptManager ID="asm" runat="server" />
Next, add a panel which serves as the modal popup. A button is used to close the popup:
[!code-aspxMain]
1: <asp:Panel ID="ModalPanel" runat="server" Width="500px">
2: ASP.NET AJAX is a free framework for quickly creating a new generation of more
3: efficient, more interactive and highly-personalized Web experiences that work
4: across all the most popular browsers.<br />
5: <asp:Button ID="OKButton" runat="server" Text="Close" />
6: </asp:Panel>
Whenever the popup is shown, it shall be positioned at a certain place in the page. For this task, a client-side JavaScript function is created. It first tries to access the panel. If it succeeds, the panel’s position is set using CSS and JavaScript (change the position of the popup at will). However the ModalPopupExtender
control also tries to position the popup. Therefore, the JavaScript code repeatedly positions the popup, every tenth of a second.
[!code-htmlMain]
1: <script type="text/javascript">
2: var id = null;
3: function movePanel()
4: {
5: var pnl = $get("ModalPanel");
6: if (pnl != null)
7: {
8: pnl.style.left = "50px";
9: pnl.style.top = "50px";
10: id = setTimeout("movePanel();", 100);
11: }
12: }
As you can see, the return value of the setTimeout()
JavaScript method is saved in a global variable. This allows to stop the repeated positioning of the popup on demand, using the clearTimeout()
method:
[!code-javascriptMain]
1: function stopMoving()
2: {
3: clearTimeout(id);
4: }
5: </script>
Now all that is left to do is to make the browser call these functions whenever appropriate. The movePanel()
JavaScript function must be called when the button is clicked that triggers the panel:
[!code-aspxMain]
1: <div>
2: <asp:Button ID="btn1" runat="server" Text="Launch Modal Popup"
3: OnClientClick="movePanel();" />
4: </div>
And the stopMoving()
function comes into play when the popup is closed this can be triggered in the ModalPopupExtender
control:
[!code-aspxMain]
1: <ajaxToolkit:ModalPopupExtender ID="mpe" runat="server"
2: TargetControlId="btn1" PopupControlID="ModalPanel" OkControlID="OKButton"
3: OnOkScript="stopMoving();" />
The modal popup appears at the designated position (Click to view full-size image)
|