Monday, September 29, 2008

Run a Server Side Code and Open a Popup Window onClick of a Link in Asp.net


There are 3 ways we can achieve this :

1) Create a LinkButton and add both client side as well as server side onclick event handlers :

<LinkButton ID="LinkButton1" runat="server" onclick="LinkButton1_Click>LinkButton <asp:LinkButton>

protected override void OnLoad(EventArgs e)
{
LinkButton1.Attributes.Add("onclick", "window.open('test.aspx');");
}

protected void LinkButton1_Click(object sender, EventArgs e)
{
//Server side code here
}

(Problem : Both the events occur simultaneously so if we have a scenario wherein we want the popup to open after the server side code is executed, this isn’t useful)

2) Render the script using Response.Write :

protected void LinkButton1_Click(object sender, EventArgs e)
{
//Server side code here

Response.Write("&lt;script&gt;");

Response.Write("window.open('test.aspx','_blank')");

Response.Write("&lt;/script&gt;");
}

(Problem : In some browsers the CSS of the background window gets affected with this solution)


3) Use the Page.ClientScript.RegisterClientScriptBlock method :

protected void LinkButton1_Click(object sender, EventArgs e)
{
//Server side code

string _url = "test.aspx";

this.Page.ClientScript.RegisterClientScriptBlock(
this.GetType(),
"openNewWindow", "window.open(\"" + _url + "\");",
true);
}

The 3rd one is the most efficient way in my view.

2 comments:

Anonymous said...

Nice post and this post helped me alot in my college assignement. Thank you for your information.

DotNetQuery said...

Hey well thanks a lot for the code...
I was trying this since 2 am...finally i reached at your blog and got the exact answer..
thanx a lot

Mayank Pathak...

AddIn