Sharepoint - Possible to close a Modal Dialog from code behind?

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>

Tags:

Modal Dialog