C# Postback - set text on page after sending download - c#

I have a form that on submit, downloads a generated csv file. I have an asp:Literal on the page as a placeholder for loading text:
<div id="loading-text">
<asp:Literal ID="litLoadingText" runat="server"></asp:Literal>
</div>
$("input[type=submit]").on("click", function() {
//$(".loading-modal").show();
$("#loading-text").html("Loading...");
});
and I'm trying to change the text after the download is complete to say "Done!" or just get removed:
Response.Clear();
Response.Buffer = true;
var fileName = !String.IsNullOrEmpty(txtFileName.Value) ? txtFileName.Value : "ContentExport";
Response.AddHeader("content-disposition", String.Format("attachment;filename={0}.xls", fileName));
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
litLoadingText.Text = "Done!";
}
but the text doesn't change. I'm pretty sure this is because of the downloading, where I'm doing Response.End() and whatnot, but I'm not sure how to handle it. Is there a way to do this in C#, or is there a Javascript method I could use instead to detect when the download is done? What would be the best approach?

The problem is described here: https://support.microsoft.com/en-us/help/312629/prb-threadabortexception-occurs-if-you-use-response-end-response-redir
Cause
The Response.End method ends the page execution and shifts the execution to the Application_EndRequest event in the application's event pipeline. The line of code that follows Response.End is not executed.
This problem occurs in the Response.Redirect and Server.Transfer methods because both methods call Response.End internally.
Resolution
To work around this problem, use one of the following methods:
For Response.End, call the HttpContext.Current.ApplicationInstance.CompleteRequest method instead of Response.End to bypass the code execution to the Application_EndRequest event.
For Response.Redirect, use an overload, Response.Redirect(String url, bool endResponse) that passes false for the endResponse parameter to suppress the internal call to Response.End. For example:
Response.Redirect ("nextpage.aspx", false);
If you use this workaround, the code that follows Response.Redirect is executed.
For Server.Transfer, use the Server.Executemethod instead.

Related

WebForm Server.Transfer - Variables are not being recorded in downloaded files

I'm using Server.Transfer and in the 2nd place I have a number of labels that are updated with a Request.Form["textbox_text"];
This all works really well, but the problem is I also want to write the content in that textbox to file
like a word document using this method
Response.Clear();
Response.AddHeader("Content-disposition", "attachment; filename=Word.doc");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.ContentType = "application / vnd.ms -word";
Response.ContentEncoding = System.Text.Encoding.Unicode;
Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
htw.Write("<table><h2><b>[ Text ]</b></h2><br>" + TextBox_name.Text + "</table>");
Response.Write(sw.ToString());
Response.End();
But whenever I check the file it will not have anything written on it. I've even tried to save the value of a Request.Form to a static variable and then write that variable but without any success.
How are you using Server.Transfer()? Post that code, make sure you are using the overload that preserves the form values:
Server.Transfer("page.aspx", true);

How to display pdf file in a seperate tab in a browser?

I have tried a code to open a pdf file in a web browser. It give to allows me to open the file through pdf reader no in the browser. Almost all the codes i found over the internet are also same as this code. But this code doesn't work as i expected.
Help me to figure out the problem in here. I'm using a link button in the aspx.
Here is my code
aspx code
<asp:LinkButton ID="pdfViewLOP" runat="server" Style="margin-left: 10px" OnClick="pdfViewLOP_Click" >View PDF</asp:LinkButton>
aspx.cs
Response.Write(string.Format("<script>window.open('{0}','_blank');</script>", "viewPDF.aspx"));
Code of the new page which pdf should be displayed
string name=Session["name"].ToString();
int refNo = Convert.ToInt32(name);
string FilePath = Server.MapPath("~/filesPDF/" + refNo + ".pdf");
WebClient User = new WebClient();
Byte[] buffer = User.DownloadData(FilePath);
if (buffer != null)
{
Response.Clear();
Response.ContentType = "application/pdf";
Response.AddHeader("content-length", buffer.Length.ToString());
Response.BinaryWrite(buffer);
}
How if you directly create a hyperlink with target _blank and path of file as a href of hyperlink.
So the result hyperlink generated inside the html page is
View PDF

Save Window at Excel Report in C#

I have a working Excel Report code. Still, when I click the button the file goes directly to my download folder, without giving me the option to change its name or selecting where I want to save it.
Code is the following:
public void GetExcel()
{
var list = (IList<LeaseViewModel>)Session["currentList"];
var grd = new GridView { DataSource = list, AutoGenerateColumns = true };
grd.DataBind();
Response.ClearContent();
Response.AddHeader("Content-type", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
Response.AddHeader("content-disposition", "attachment;filename=Leases.xls");
Response.ContentType = "application/excel";
var swr = new StringWriter();
var tw = new HtmlTextWriter(swr);
grd.RenderControl(tw);
Response.Write(swr.ToString());
Response.Flush();
Response.End();
tw.Close();
swr.Close();
}
Can somebody please indicate what should I change in order to have the window popping?
Thanks a lot.
Thanks for everybody highlighting this is a browser-configuration issue.
I thought that once I have the definition of the default name in the code I could also define it to always ask what is the name I want. I tested in different browsers though, and fact is you were right, thanks for identifying it and noticing me.
Regarding the default name issue, here is how I solve it:
Before:
Response.AddHeader("content-disposition", "attachment;filename=Leases.xls");
After:
Response.AddHeader("content-disposition", "attachment;filename=" + Session["listName"] + "_Report.xls");
Now regardless the report I export, the name is always customized.
Hope it helps other newbies like me (:

How to open PDF file in a new tab or window instead of downloading it (using asp.net)?

This is the code for downloading the file.
System.IO.FileStream fs = new System.IO.FileStream(Path+"\\"+fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] ar = new byte[(int)fs.Length];
fs.Read(ar, 0, (int)fs.Length);
fs.Close();
Response.AddHeader("content-disposition", "attachment;filename=" + AccNo+".pdf");
Response.ContentType = "application/octectstream";
Response.BinaryWrite(ar);
Response.End();
When this code is executed, it will ask user to open or save the file. Instead of this I need to open a new tab or window and display the file. How can I achieve this?
NOTE:
File won't necessary be located in the website folder. It might be located in an other folder.
Response.ContentType = contentType;
HttpContext.Current.Response.AddHeader("Content-Disposition", "inline; filename=" + fileName);
Response.BinaryWrite(fileContent);
And
<asp:LinkButton OnClientClick="openInNewTab();" OnClick="CodeBehindMethod".../>
In javaScript:
<script type="text/javascript">
function openInNewTab() {
window.document.forms[0].target = '_blank';
setTimeout(function () { window.document.forms[0].target = ''; }, 0);
}
</script>
Take care to reset target, otherwise all other calls like Response.Redirect will open in a new tab, which might be not what you want.
Instead of loading a stream into a byte array and writing it to the response stream, you should have a look at HttpResponse.TransmitFile
Response.ContentType = "Application/pdf";
Response.TransmitFile(pathtofile);
If you want the PDF to open in a new window you would have to open the downloading page in a new window, for example like this:
View PDF
this may help
Response.Write("<script>");
Response.Write("window.open('../Inventory/pages/printableads.pdf', '_newtab');");
Response.Write("</script>");
You have to create either another page or generic handler with the code to generate your pdf. Then that event gets triggered and the person is redirected to that page.
Here I am using iTextSharp dll for generating PDF file.
I want to open PDF file instead of downloading it.
So I am using below code which is working fine for me.
Now pdf file is opening in browser ,now dowloading
Document pdfDoc = new Document(PageSize.A4, 25, 10, 25, 10);
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
Paragraph Text = new Paragraph("Hi , This is Test Content");
pdfDoc.Add(Text);
pdfWriter.CloseStream = false;
pdfDoc.Close();
Response.Buffer = true;
Response.ContentType = "application/pdf";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.End();
If you want to download file,
add below line, after this Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=Example.pdf");
you can return a FileResult from your MVC action.
*********************MVC action************
public FileResult OpenPDF(parameters)
{
//code to fetch your pdf byte array
return File(pdfBytes, "application/pdf");
}
**************js**************
Use formpost to post your data to action
var inputTag = '<input name="paramName" type="text" value="' + payloadString + '">';
var form = document.createElement("form");
jQuery(form).attr("id", "pdf-form").attr("name", "pdf-form").attr("class", "pdf-form").attr("target", "_blank");
jQuery(form).attr("action", "/Controller/OpenPDF").attr("method", "post").attr("enctype", "multipart/form-data");
jQuery(form).append(inputTag);
document.body.appendChild(form);
form.submit();
document.body.removeChild(form);
return false;
You need to create a form to post your data, append it your dom, post your data and remove the form your document body.
However, form post wouldn't post data to new tab only on EDGE browser. But a get request works as it's just opening new tab with a url containing query string for your action parameters.
Use this code. This works like a champ.
Process process = new Process();
process.StartInfo.UseShellExecute = true;
process.StartInfo.FileName = outputPdfFile;
process.Start();

Export All Rows of Paged ListView to Excel

In ASP.NET 4.0 webforms, I'm trying to export a paged ListView control to an Excel file by un-paging the ListView's (trucks) datasource:
dsTrucks.EnablePaging = false;
For a non-paged ListView control, I can get it to work.
Here's the attempt to "un-page" and then export the ListView control:
// Nuke the current page.
Response.Clear();
// Setup the response header.
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Trucks.xls");
Response.ContentType = "application/vnd.ms-excel";
Response.Charset = "";
// Turn off view state.
this.EnableViewState = false;
// Create a string writer.
var stringWriter = new StringWriter();
// Create an HTML text writer and give it a string writer to use.
var htmlTextWriter = new HtmlTextWriter(stringWriter);
// Disable paging so we get all rows.
dsTrucks.EnablePaging = false;
// Render the list view control into the HTML text writer.
listViewTrucks.DataBind();
listViewTrucks.RenderControl(htmlTextWriter);
// Grab the final HTML out of the string writer.
string output = stringWriter.ToString();
// Write the HTML output to the response, which in this case, is an Excel file.
Response.Write(output);
Response.End();
There's no error but the output in the Excel file is still just one page of the ListView control instead of all rows.
Any ideas on where to start to get this to work?
Thanks,
Adam
Just a guess, but it might be that EnablePaging works only on the control's OnInit() and it is too late by the time you call it from your code.
Perhaps you could you set the PageSize some MAXINT value and force all results into one single page?

Categories