|
Use RegisterClientScriptBlock To Popup New Window From ASP.Net Page
 |
 |
| Figure 1 |
Figure 2 |
A lot of time you come across a situation where you need to popup a new window
to the users corresponding to some action on the page. In good old classic ASP
days we all used to accomplish it by using window.open client side
javascript method. In ASP.Net the method is still the same but now its
has gotten better. Page class has a wonderful method RegisterClientScriptBlock
that does the job of emitting client script on the page. What this method does
is that it emits all the text that you specify as the second parameter to this
method on the page right after opening <form> tag. Therefore
the script gets executed right after the opening tags. Therefore it is
important that you don't put any code that requires access to any variables
that will be generated toward the end of the page because they will not exist
at the time of script execution.
The project attached with this article demonstrates how this concept is used on
web site where a user provides his or her email address and choose to either
subscribe or unsubscribe for the mailing list. When user clicks on Submit
button (Figure 1), a new window is popped up with the appropriate message
(Figure 2) telling the user about their action. On pop window message we use RegisterClientScriptBlock
method to register client-side script that will close the windows when user
clicks on Close button (Figure 2).
Folowing code is used to pop-up new window
private void OnSubmit(object sender, System.EventArgs e)
{
string strQS = "NotifySubscriber.aspx?email=";
strQS += Email_TextBox.Text;
strQS += "&action=";
if (Subscribe_Radio.Checked)
{
strQS += "1";
}
else
{
strQS += "0";
}
StringBuilder strScript = new StringBuilder();
strScript.Append("<script language=JavaScript>");
strScript.Append("window.open('" + strQS + "', \"\",\"height=100,width=400,left=0,top=0,toolbar=no,menubar=no\");");
strScript.Append("</script>");
RegisterClientScriptBlock("subscribescript", strScript.ToString());
}
Notice that we have included the opening and closing <script> tags in the
the script. This is very important otherwise the script text will be displayed
on the page as such and it will not be executed.
|