Ketone Cops

March 26, 2008

Ajax, an update panel and opening a new window

Filed under: Ajax,ASP.NET 2.0,programming,UpdatePanel — delroger @ 1:51 pm

Since this post is getting quite a few views, just thought I’d add a quick summary of this article if you don’t want to read it all. So here you go: if you want to open a new window from the code-behind page when your function or sub is being called from an AJAX Update Panel, you can do it like this (here your Update Panel is called UpdatePanel1 and you’re opening a PDF)…

ScriptManager.RegisterClientScriptBlock(Me.UpdatePanel1, Me.UpdatePanel1.GetType(), "AnyScriptNameYouLike", "window.open('http://www.yourwebsite.com/YourFolder/YourDocumentOrWebpage.pdf');", True)

And here’s the rest of the original post…

I recently found a problem when using an Ajax Update Panel when I wanted to open a PDF document from the code-behind page.  Without the Ajax, I could simply have added a Response.Write with a javascript window.open function, or I could have used a Literal and written the javascript in much the same way, like this:

Response.Write("<script language='javascript'> window.open('http://website/folder/newdocument.pdf'); </script>")

or this (assuming a Literal control called ltlOpenPdf):

ltlOpenPdf.Text = "<script language=""javascript"">window.open('http://website/folder/newdocument.pdf');</script>"

However, the Response.Write is forbidden in Ajax and produces an error, while the Literal apparently did nothing at all.

Finally I worked out that I could open the new document by using a RegisterClientScriptBlock, most importantly passing the Update Panel as the first parameter where the Page is expected, and the Update Panel’s type as the second parameter, as you will see below.

The Update Panel is called UpdatePanel1. A new PDF has been created and saved to a folder called ‘pdffolder’ and the name of the PDF is dynamically created. The root of the website is also being added dynamically so that it will work equally on the development and the production server. (In reality, the name of the folder that contains the PDFs is also dynamically set, captured from the web.config file using System.Configuration.ConfigurationManager.AppSettings)

Dim docGuid As String = Guid.NewGuid().ToString()
'Do pdf creation stuff here...
Dim sb As StringBuilder = New StringBuilder("")
Dim strRoot As String
strRoot = Request.Url.GetLeftPart(UriPartial.Authority)
sb.Append("window.open('" + strRoot + "/pdffolder/" + docGuid + ".pdf" + "');")
ScriptManager.RegisterClientScriptBlock(Me.UpdatePanel1, Me.UpdatePanel1.GetType(), "NewClientScript", sb.ToString(), True)

The only thing to watch out for with this is that it may be classified as a popup by some blockers and prevented from opening, but then that’s almost inevitable with a window created in code.

Create a free website or blog at WordPress.com.