Friday, May 19, 2006

Modal windows in Javascript

Problem:
Need to show a modal form in a web application to capture some data
and return those data back to the parent form [base form].

Issues:
In javascript window.showModalDialog() is used to show modal windows.
But this does not work as expected in window.open().

Solution
To make the solution much easier I'll be using an example.
I'll be having following files and their names explain their functionality.

ParentForm.aspx/ParentForm.aspx.cs
ModalForm.aspx/ModalForm.aspx.cs
Javascripts.js

[I'll be using "[" & "]" as HTML open/close tags due to publishing
restrictions. Please do replace them with correct tags]

ModalForm.aspx

[HEAD]
[base target="_self"]
[/HEAD]

[body]
[form id="Form1" method="post" runat="server"]

[asp:Button id=btnDone runat="server" Text="Done" /]
[asp:TextBox id=txtValue runat="server" /]

[/form]
[/body]


ModalForm.aspx.cs

private void Page_Load(object sender, System.EventArgs e)
{

// ---------------

// replace "[" & "]" with correct tags.
string script = @"[script language=javascript]
function reloadParent() {
window.returnValue=
document.getElementById('" + txtValue.ID + "').value;"
+ @"window.close();
}
[/script]";

this.RegisterClientScriptBlock("reloadParent", script);

btnDone.Attributes.Add("OnClick", "reloadParent()");

// Following three lines are quite important.
// Usually modal forms are cached.
// So when you invoke the modal form for the second time, it's
// Load() event won't fire. Following code fixes this.

Response.Equals(0);

Response.Cache.SetNoStore();

Response.AppendHeader("Pragma","no-cache");
}

ParentForm.aspx

[HEAD]

[script language="javascript"
src="Javascripts.js" type="text/javascript"]
[/script]

[/HEAD]

[body]
[form id="Form1" method="post" runat="server"]

[INPUT onclick="InvokeModalForm()"
type="button" value="INVOKE"]
[asp:TextBox id=txtValueFromModal runat="server" /]

[/form]
[/body]

Javascripts.js

function InvokeModalForm()
{

rc = window.showModalDialog('ModalForm.aspx,"window",
"center:yes;dialogHeight:460px;
dialogWidth:330px;resize:no;help:no;status:no;scrollable:no");

if (rc!=null)
{
document.getElementById('txtValueFromModal').value = rc;

__doPostBack('','');

}
}

No comments:

Post a Comment