Close Browser Window after Form Post - asp.net

Here's my situation.
I have a button on my ASP.NET webform. This button creates a new browser window pointing to a page which has a lot of hidden fields (which are dynamically generated). This form submits itself to SQL Reporting Services on the bodies onload event. This works fine and the report is displayed in this new window.
However, now I want to still POST a form to SQL Reporting services but I want to get back an excel spreadsheet. So I add another hidden input with a name of rs:Format and value of Excel. This works and the user gets the option to download the excel file.
However they are now stuck with the extra window that was created. How do I get around this? I've tried creating the dynamic form and POST in the same window, but then they see the (empty) page with the form, and not the page they generated the report from. I've tried closing the window that I've created but I don't know where to put the javascript to do this. If I put it on the onload, then the window closes without the form being submitted.
Any ideas for what to do here?
Edit: What I was doing here wasn't the best way of getting the result I needed. I ended up using a WebRequest to get the excel report from Reporting Services instead posting a form, therefore I didn't need the second window afterall.

Don't close the browser. It belongs to the user, even if you opened it. Closing it can make them mad.
Do redirect to a page the communicates to the user that you're done with the window. There you can provide a (javascript-based) link that make closing the browser a little easier if you want, though closing a browser window is generally pretty easy.

By the way, if the popup doesn't contain any useful output, what you may want to do is submit your form into a small Iframe within the page. This way there's no need to close a window, as the frame can be made invisible.

When user wants an Excel file, there's no need to pop up another window. I assume selection of Excel file or HTML report is done in some HTML control like a radio button or a checkbox. So, before doing anything, check the value of that radiobutton/checkbox with javascript and do the appropriate action. Something like:
function getReport(excelFormat)
{
if (excelFormat)
document.form1.target = '_blank';
else
document.form1.target = '_self';
document.form1.submit();
}

What if the button did an Ajax request back to the original page and got the hidden field values. You could then construct another form on the page with the hidden fields using javascript and submit it -- with the download option. Since the request will return an application/ms-excel file, it shouldn't refresh the current page but the download should still occur. You'd need to make sure that the button click didn't cause a postback by returning false from the client-side function. Note that this only works if the post of the generated form results in a download, not a new html page.
<script type="text/javascript">
function submitReport( button ) {
PageMethod.SubmitReport(onSuccess,onFailure,{ control: button });
}
function onSuccess(values,ctx) {
var form = document.createElement('form');
form.action = reporting-services.url;
form.method = 'post';
document.body.appendChild(form);
.... add hidden fields to form from returned values
form.submit();
document.body.removeChild(form);
}
function onFailure(error,ctx) {
... pop up some error message....
}
</script>
...
<asp:Button runat="server" id="reportButton" ClientClick="submitReport(this);return false;" Text="Report" />

Generally it's ok to close any popup window that your app has created.
This can be done with window.close() (which will pop up a confirmation if the window was not created by script).
If you want to be sure that the download is successful before closing the window, you will need to perform some server-side magic - have your server keep track of the download in progress, and poll it via AJAX from the popup window until the download completes.
Once the server tells you it's done, the window can be closed.

Related

Validation using navigation

I have some pages in my website and a left menu control. Control helps to navigate from one page to another.
My query is -> While user try to navigate to another page, I want to impose some validation like in the current page if the form is not saved, user will be asked to save it by using a confirm messagebox and if user presses no button, then user will be allowed to navigate otherwise, system will first save the details and then navigate.
Edit - My page is a content page, I meant, this is using a master page.
Use the following steps
window.onbeforeunload = confirmExit;
and a function that stops/continue the page execution.
function confirmExit() {
var email= document.getElementById("email");
if (email.value != "")
return "You have attempted to leave this page. If you have made any changes to the fields without clicking the Save button, your changes will be lost. Are you sure you want to exit this page?";
}
The way I would do this is to have an onbeforeunload javascript event fire which gives the user the choice to save the form. I personally would also poll the form saving data back whist they are completing it. I think this is the method SO uses.
There is a pretty decent example over on Code Project that may help http://www.codeproject.com/KB/aspnet/AutoSaveFormData.aspx
EDIT:
If you only want to call the save method you can mark it with the [WebMethod] filter and call it using XmlHttpRequest or jQuery's $.post

How to close aspx page that is redirect from handler

I am in critical situation.
In my application I try to close opened window using javascript function.
function Close_Window() {
var myWin = window.open('', '_parent', '');
myWin.close();
}
this function is used in 3 aspx pages.
That page will open from mail means my application is used for sending Mail.
In that such as normal newsletter there will be three footer links like UnSubscribe,Forward A Friend,Change E-Mail address.
So on click of close button for above these three pages I had written that code.
The page will be opened from “ashx” file. And I try to close it using Javascript.
So close button is working when I direct click on the above three links.
But by right clicking on that I open it in new window or new tab close button is not working.
So please give me solution that how can I close aspx page using javascript or in code behind.
My purpose is page should be close any how by javascript or by code behind.
Note : I am opening that page using ashx handler.
If you want total control of opening and closing windows, keep the control and do not transfer the control to the browser. The behaviour of Html is well defined by W3C. The behaviour of new browser windows/tabs will vary between different browsers, and probably in the future.
Why do you open and close a page directly?
Probably you want to execute a GET request on the server to trigger some action. Take a look at the jQuery get method. So you can execute your request, without the need to open/close a new page.
If you want the user to make a choice, after clicking the link, I would work with a jQuery modal dialog. This pops up a dialog, but inside the current HTML page. Therefor you are in control of closing the dialog.
If you open a new window/tab the browser is in control, and the behaviour depends on the browser / user settings combination.

Unable to call Javascript from Codebehind

I know my issue is very common and similar types has been asked many times over here, but my problem is somewhat different. I am working on ASP.Net 4.0 web application where on my required page i have ajax toolkit 4 calendar control, toolkitscript manager and few asp controls. Now from that pop up i am doing a save operation on button click. What i want is to close popup window after successful save. Problem is not in saving but after saving , automatically closing the popup screen. I have tried the following ways:
RegisterStartUpScriptBlock(this.GetType,"closeForm","return window.close();") and all other required params
ClientScript.RegisterStartUpScript()--- alongwith params and with both return window.close(); and window.close() also with self.close();
Also i have under the title tag...
I think i have tried all the ways , i can. I feel i am lost. Please help me out....
if your using a script manager on the page...
first create a function to close the calendar in js in your html...
function closeCalendar(){
....
}
then on the codebehind use this to call that js function
string script = string.Format(#"closeCalendar()");
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
If the popup you mean is the AJAX Toolkit Modal Popup, you can just call popup.Hide(); in codebehind.
If it is a browser window, did you try to remove the return part from your code?
Note that windows.close() will not work unless the popup is opened via window.open();
Also, did you try to just put the script tag inside PlaceHolder control that is hidden (server-side Visible=false) by default and only shown when you need?

Implementing Back button functionality in asp.net

i need to implement a back button for my asp.net website.I am able to use the javascript method to acheive my requirement.But using this method sometimes I need to click on the back button multiple number times to go back to the previous page.It may be because we are using jquery tabs in our website.To focus on a particular tab,other than the 1st tab on page load I am using Page.ClientScript.RegisterStartupScript(....).So I am unable to take the user back to the previous page with just one click.
I also tried with asp.net-C# methods mentioned in the following link.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=89
I am able to go back to the previous page, but its state is being lost.Could someone please help me in acheiveing my requirement?
Details:
I have page1.aspx,page2.aspx(which contains jquery tabs view/edit).
In the page1.aspx there are 2 buttons(View,Edit).If I click on view button it takes me to page2.aspx View tab(1st tab) and if I click on the edit button it has to take me to page2.aspx with Edit tab loaded.both View/Edit tabs contain back button.
Also from the View tab I can navigate to the Edit tab,by clicking on another Edit button present in it.
Thanks.
The methods you have covered in your question are essentially what is available to you.
You can either
1. Provide a link that uses javascript to make the client go back a page.
2. Provide a link that posts back to the server that redirects you back a page.
I am not sure why the jquery in your webform as described in your question is causing you to click more that once to go back. If you know that it will always take 2 clicks to go back you could try this method:
javascript: window.history.go(-2)
When you are using the postback/redirect method you will always be using a http GET method to retrieve the page you are returning too. If you want to maintain state you will have to do this manually i.e. save the values when leaving the page somewhere, like session or a temporary database, and when returning to the page, during the page load, check to see if the user has these values saved and pre-populate them.
I've done something similar (with automatic redirections though) and I had to keep track of the number of pages to go back in my ViewState (or Session if you're jumping from page to page):
code-behind
public void Page_Load()
{
Session["pagesToGoBack"] = ((int)Session["pagesToGoBack"])++;
}
mark-up:
<input type="button" value="Back" onclick='javascript:history.go(<%= Session["pagesToGoBack"] %>);' />
Be careful to reset the session variable when needed
Made me feel a bit dirty but it worked :)

asp.net make button show different view of MultiView AND download a file

I have a page on my site on which users have to fill out details before they can download a document. The user details section is on the first view in a MultiView control.
After filling out their details I'd like the user to click a button which will show them a file download prompt (I've done this successfully with an ashx handler) then redirect them to the second view page of the MultiView which will say "thank you for downloading" or something like that.
I've tried the usual Response.Redirect("~/DownloadHandler.ashx"); within the button click event handler, but obviously this prevents the page completing the postback and showing the last page of the MultiView.
Is there a way around this, or should I just change my UI to accommodate this?
EDIT:
I've concluded that it's better to just provide a hyperlink to the document (on my confirmation page, and change the wording accordingly) as this provides a consistent user experience independent of the browser they're using.
Go ahead and take them to the second view of the MultiView. Add a javascript method that will download the document, and trigger it from your codebehind.1 E.g.,
In your page:
<script>
function downloadFile(url) {
window.location = url;
//you could also try window.open(url, 'Download')
}
</script>
In your code behind:
script = string.Format("downloadFile('{0}');", "DownloadHandler.ashx");
Page.ClientScriptManager.RegisterStartupScript(typeof(Page), "download", script, true);
You could also add a delay (using setTimeout) before the file is downloaded.
More info:
Initiating a file download that works well, even in IE?

Resources