Introduction
A very simple method to popup a window on button click is, write the JavaScript code at the client side. Following code demonstrates this method.
<form>
<input type="button" value="Click Me!" onClick="window.open('hello.html')">
</form>
The disadvantages of this method are:
- Code is visible at client side.
- Code and HTML are not separate. Thus maintenance is tedious.
With ASP.NET these disadvantages disappear. Let's take a look how this can be done with ASP.NET.
The popup html page
The first page that we will create is the 'hello.html' page. This is the page that will be popped up in the new window.
<html>
<body>
<h1>Hello, World!</h1>
</body>
</html>
The aspx Page
Let us create an ASP.NET Web Form with a single button.
<form runat="server">
<asp:button id="button1" onclick="button1_click"
runat="server" Text="Click Me!"></asp:button>
</form>
Now we will add the C# script code to handle our button click event. Off course, you can create this with the code-behind facility.
<script language="C#" runat="server">
string buildScript(string id, string output_page)
{
string myScript = "\n";
myScript += "<script language="'javascript'" id='" + id + "'>\n";
myScript += "window.open('" + output_page + "');\n";
myScript += "</" + "script>\n";
return myScript;
}
void button1_click(object sender, EventArgs e)
{
string script_id = "popup";
string myScript = buildScript(script_id, "hello.html");
if(!IsStartupScriptRegistered(script_id))
{
RegisterStartupScript(script_id,myScript);
}
}
</script>
<form runat="server">
<asp:button id="button1" onclick="button1_click"
runat="server" Text="Click Me!"></asp:button>
</form>
Let us call this page 'popupexample.aspx'.
The entire thing explained!
Our function buildScript
builds the script that will be emitted to the client side. button1_click
handles the button.OnClick
event. The Page.RegisterStartupScript
and Page.RegisterClientScriptBlock
are used to emit the script to the client side. With Page.RegisterClientScriptBlock
, the client-side script is emitted just after the opening tag of the Page object's <form runat="server">
element. With Page.RegisterStartupScript
, the client-side script is emitted just before the closing tag of the Page object's <form runat="server">
element.
Page.IsClientScriptBlockRegistered
: Call this method before calling Page.RegisterClientScriptBlock/Page.RegisterStartupScript
to avoid unnecessarily assembling the client-side script. This is particularly important if the script requires a large amount of server resources to create.
References
MSDN.
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.