I am popping up a Custom Application Page using a call to SP.UI.ModalDialog.showModalDialog. Is there a way that I can close the dialog from the code behind after a user clicks a button?
4 Answers
Found a solution. Add this to the end of the button click event:
Context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
Context.Response.Flush();
Context.Response.End();
You can also add the SP.UI.ModalDialog.close(SP.UI.DialogResult.OK)
event on your button or otherwise make some javascript logic that triggers this event if no errors occured.
Examples 1:
<asp:Button ID="Submit" runat="server" OnClientClick="SP.UI.ModalDialog.close(SP.UI.DialogResult.OK)" />
Example 2:
<script type="text/javascript">
// In case you use jquery ajax for some kind of postback
$.ajax({type: "POST",
url: some_url,
data: {},
contentType: ...,
success: function() {SP.UI.ModalDialog.close(SP.UI.DialogResult.OK);},
error: function() {SP.UI.ModalDialog.close(SP.UI.DialogResult.invalid);}
});
</script>
Yes it is possible to close the Modal Dialog from code-behind.
Simply add the below code to your button click event and you are done.
HttpContext context = HttpContext.Current;
if (HttpContext.Current.Request.QueryString["IsDlg"] != null)
{
context.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup()</script>");
context.Response.Flush();
context.Response.End();
}
Better still create an extension method on the Page object
/// <summary>
/// Closes the SP Dialog down. Note this will only work when the button triggering the close action does not reside in an Update Panel
/// </summary>
/// <param name="Page"></param>
public static void CloseSPDialog(this Page Page)
{
Page.Response.Write("<script type='text/javascript'>window.frameElement.commitPopup();</script>");
Page.Response.Flush();
Page.Response.End();
}
And call like this
void btnClose_Click(object sender, EventArgs e)
{
//Do stuff here
Page.CloseSPDialog();
}