Tutorial :Response.redirect on Popup to go to Main page



Question:

I have a pop up page that opens when I select a link on the parent window. If some exception occurs in page loaded handler of the pop up, then the error should go to parent window, not the pop up page. If an exception does not occur in the pop up page, it will load the pop up only with the contents.

An error message is coming from one Asp page.

The code in the catch block of popup page:

catch(Exception ex)  {      Response.Redirect("");      Response.End();  }  


Solution:1

You can't use Response.Redirect to decide where the page will be loaded. That is decided before the request is sent to the server, so when the server code starts to run it's already too late to change where the page will go.

If you want to close the popup and load a page in the parent window instead, you have to write Javascript code to the popup that does that.

Example:

catch (Exception ex) {     Response.Write(        "<html><head><title></title></head><body>" +        "<script>" +        "window.opener.location.href='/ErrorPage.aspx?message=" + Server.UrlEncode(ex.Message) + "';" +        "window.close();" +        "</script>" +        "</body></html>"     );     Response.End();  }  


Solution:2

If you are handling the error in the catch block, what you can do - declare a javascript variable and set the error text in that variable.

var errorDescription = ""; //Will hold the error description (in .aspx page).  

If error occurs, you do this in the catch block -

try  {      //Code with error  }  catch(Exception ex)  {      ScriptManager.RegisterStartupScript(this, this.GetType(), "ErrorVariable", string.Format("errorDescription = '{0}'; CloseWindow();", ex.Message), true);  }  

What the above code will do - set the error description, and call the CloseWindow() function on your aspx page. The function will contain the following lines of code -

function CloseWindow() {      window.parent.window.SetError(errorDescription);      self.close();  }  

This function will call the parent window's function and close itself. The SetError() function can display the error in whatever fashion you like.


Solution:3

I think it would be a better user experience to use a javascript popup and do the request via AJAX rather than use a new window and a full page request cycle. Doing it in javascript gives you the ability to keep all the interaction on the same page and would make it trivial to get your error message in the "main" interface. Among many other ways to do this you could use jQuery to provide both the AJAX interface and the dialog plugin to manage the modal dialog.


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »