Handling Postbacks from a ModalPopup (VB)
The ModalPopup control in the AJAX Control Toolkit offers a simple way to create a modal popup using client-side means. Special care must be taken when a postback is created from within the popup.
Overview
The ModalPopup control in the AJAX Control Toolkit offers a simple way to create a modal popup using client-side means. Special care must be taken when a postback is created from within 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. There, the user can enter a name and an email address. A button is used to close the popup and save the information. Note that the OnClick
attribute is set so that a postback occurs when this button is clicked:
[!code-aspxMain]
1: <asp:Panel ID="ModalPanel" runat="server" Width="500px">
2: Name: <asp:TextBox ID="tbName" runat="server" /><br/>
3: Email: <asp:TextBox ID="tbEmail" runat="server" /><br/>
4: <asp:Button ID="OKButton" runat="server" Text="Save"OnClick="SaveData" />
5: </asp:Panel>
The page itself consists of two labels for exactly the same information: name and email address. A button is used to trigger the modal popup:
[!code-aspxMain]
1: <div>
2: Contact Information:
3: <asp:Label ID="lblName" runat="server" Text="AJAX Fanatic"/><br />
4: <asp:Label ID="lblEmail" runat="server" Text="ajax@fanatic"/><br />
5: <asp:Button ID="btn1" runat="server" Text="Edit"/>
6: </div>
In order to make the popup appear, add the ModalPopupExtender
control. Set the PopupControlID
attribute to the panel’s ID and TargetControlID
to the button’s ID:
[!code-aspxMain]
1: <ajaxToolkit:ModalPopupExtender ID="mpe" runat="server" TargetControlID="btn1" PopupControlID="ModalPanel" />
Now whenever the Save
button within the modal popup is clicked, the server-side SaveData()
method is executed. There, you could save the entered data in a data store. For the sake of simplicity, the new data is just output in the label:
[!code-vbMain]
1: Protected Sub SaveData(ByVal sender As Object, ByVal e As EventArgs)
2: lblName.Text = HttpUtility.HtmlEncode(tbName.Text)
3: lblEmail.Text = HttpUtility.HtmlEncode(tbEmail.Text)
4: End Sub
Also, the textbox controls within the modal popup should be filled with the current name and email. However this is only necessary when no postback occurs. If there is a postback, the ASP.NET viewstate feature will automatically fill the textboxes with the appropriate values.
[!code-vbMain]
1: Sub Page_Load()
2: If Not Page.IsPostBack Then
3: tbName.Text = lblName.Text
4: tbEmail.Text = lblEmail.Text
5: End If
6: End Sub
The modal popup causes a postback (Click to view full-size image)
|