I have a problem with not getting a postback after Response.End();
So the scenario is that i will click a button, clean an xmlfile and generate a message (out msg), download the xml, and then show the message in a label on the webpage. The problem is that it doesn't do anything after Response.End().
protected void btnDoIt_Click(object sender, EventArgs e)
{
string xml = "exampleXml";
string fileName = "exampleName";
MemoryStream ms = new MemoryStream();
string msg;
var cleanXml = CleanXml(xml, out msg);
cleanXml.Save(ms);
byte[] bytes = ms.ToArray();
Response.Clear();
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xml", fileName));
Response.ContentType = "text/xml";
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
lblFeedback.Text = msg;
lblFeedback.Visible = true;
}
I tried moving the code in front of response.End(), like below, but it didn't work as well for some reason.
protected void btnDoIt_Click(object sender, EventArgs e)
{
string xml = "exampleXml";
string fileName = "exampleName";
MemoryStream ms = new MemoryStream();
string msg;
var cleanXml = CleanXml(xml, out msg);
lblFeedback.Text = msg;
lblFeedback.Visible = true;
cleanXml.Save(ms);
byte[] bytes = ms.ToArray();
Response.Clear();
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xml", fileName));
Response.ContentType = "text/xml";
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
I also tried to "Click" an invisible button to get the postback like below. Didn't work either.
protected void btnDoIt_Click(object sender, EventArgs e)
{
string xml = "exampleXml";
string fileName = "exampleName";
MemoryStream ms = new MemoryStream();
string msg;
var cleanXml = CleanXml(xml, out msg);
InvisibleButtonClick(msg)
cleanXml.Save(ms);
byte[] bytes = ms.ToArray();
Response.Clear();
Response.AddHeader("Content-Disposition", string.Format("attachment;filename={0}.xml", fileName));
Response.ContentType = "text/xml";
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
private void InvisibleButtonClick(string msg)
{
lblXmlFeedback.Text = msg;
lblXmlFeedback.Visible = true;
InvisibleButton_OnClick(new object(), new EventArgs());
}
protected void InvisibleButton_OnClick(object sender, EventArgs e)
{
}
What am i missing here?
What you do not have understand is that the return from IIS to the browser can be one stream only.
In your case, you believe that you can send two.
What is actually happened?
A. You post back some data from the web page.
B. You return some file for download from the user.
C. There the stream end and close – nothing is going to the browser any more. So there is no way the page to refress, and there is no way the data on the page to change because you send nothing any more to the page.
How to solve this.
a) You can make a handler that download the file and you only give a link in the page, a link to the handler that download the data.
b) you can make some other page that you redirect him with the message that you like to send, and there automatically with some javascript you start downloading your file.
c) you can use ajax to download your extra data, and javascript to show any message
similar answers
What is the best way to download file from server
file download by calling .ashx page
Updating a page before initiating a download?
I've developed a pdf file using itextsharp.
Pdf generation is working fine. After the pdf is created it's being downloaded.
My problem is when the user clicks on Generate PDF button , Pdf is generated and downloaded properly but postback doesn't occurs.
I want the postback to be occured because I want to Reset my Form after Pdf is generated that is Clear All Fields .
How Can I do this ?
Here is my code :
Method to Generate PDF :
public void GetPDF(string quote_num)
{
string url = FilesPath.Path_SaveFile + Session["empcd"].ToString() +"-Quotation.pdf";
Document disclaimer = new Document(PageSize.A4, 2, 2, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(disclaimer, new FileStream(url, FileMode.Create));
writer.PageEvent = new myPDFpgHandler(quote_num);
disclaimer.SetMargins(70, 10, 60, 80);
disclaimer.Open();
GenerateQuotPDF getpdf = new GenerateQuotPDF();
disclaimer = getpdf.GetPDFparams(disclaimer,quote_num, Session["empcd"].ToString(),txt_contactperson.Text,txt_contact1.Text,txt_company.Text,txt_address.Text,ddl_gene_desc.SelectedItem.ToString(),ddl_canopy.SelectedItem.ToString(),ddl_gene_type.SelectedItem.ToString(),txt_rentalamount.Text,txt_hours.Text,txt_variable.Text,ddl_terms.SelectedItem.ToString(),txt_remarks.Text,txt_technical.Text,ddl_sign1.SelectedValue,ddl_sign2.SelectedValue,txt_designation.Text,DateTime.Now);
disclaimer.Close();
System.IO.FileInfo file = new System.IO.FileInfo(url);
if (file.Exists)
{
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(url);
Response.AddHeader("content-disposition", "attachment; filename=" + Session["empcd"].ToString() + "-Quotation.pdf");
Response.AddHeader("content-length", buffer.Length.ToString());
Response.ContentType = "application/pdf";
Response.BinaryWrite(buffer);
}
}
Generate PDF Button Code :
protected void btn_submit_Click(object sender, EventArgs e)
{
if (IsValidQuotation())
{
string newQuotNum = rental_quotations.GetNewQuotNumber();
rental_quotations.AddNewQuotation(newQuotNum, Session["empcd"].ToString(), ddl_gene_type.SelectedValue.ToString(), ddl_gene_desc.SelectedValue, ddl_canopy.SelectedValue, txt_company.Text, txt_address.Text, txt_contactperson.Text, txt_designation.Text, txt_contact1.Text, txt_contact2.Text, txt_rentalamount.Text, ddl_terms.SelectedValue, txt_hours.Text, txt_variable.Text, txt_remarks.Text,ddl_sign1.SelectedValue,ddl_sign2.SelectedValue,txt_technical.Text);
GetPDF(newQuotNum);
ClearAllFields(); //this is not working
}
}
Postback is occurring since the file is being created. Try the given solution. Your GetPDF(string quote_num) function is doing two tasks that you should break into two functions.
Creating the pdf document.
Downloading the pdf file after it is done.
Now, After you have created the document, you should clear the controls and then send the file as response. Therefore do it as follows:
Create pdf file.
public void CreatePDF(string quote_num)
{
string url = FilesPath.Path_SaveFile + Session["empcd"].ToString() +"-Quotation.pdf";
Document disclaimer = new Document(PageSize.A4, 2, 2, 10, 10);
PdfWriter writer = PdfWriter.GetInstance(disclaimer, new FileStream(url, FileMode.Create));
writer.PageEvent = new myPDFpgHandler(quote_num);
disclaimer.SetMargins(70, 10, 60, 80);
disclaimer.Open();
GenerateQuotPDF getpdf = new GenerateQuotPDF();
disclaimer = getpdf.GetPDFparams(disclaimer,quote_num, Session["empcd"].ToString(),txt_contactperson.Text,txt_contact1.Text,txt_company.Text,txt_address.Text,ddl_gene_desc.SelectedItem.ToString(),ddl_canopy.SelectedItem.ToString(),ddl_gene_type.SelectedItem.ToString(),txt_rentalamount.Text,txt_hours.Text,txt_variable.Text,ddl_terms.SelectedItem.ToString(),txt_remarks.Text,txt_technical.Text,ddl_sign1.SelectedValue,ddl_sign2.SelectedValue,txt_designation.Text,DateTime.Now);
disclaimer.Close();
}
Reset the controls.
ClearAllFields();
Send the file as response.
public void SendPDF(string url)
{
System.IO.FileInfo file = new System.IO.FileInfo(url);
if (file.Exists)
{
WebClient client = new WebClient();
Byte[] buffer = client.DownloadData(url);
Response.AddHeader("content-disposition", "attachment; filename=" + Session["empcd"].ToString() + "-Quotation.pdf");
Response.AddHeader("content-length", buffer.Length.ToString());
Response.ContentType = "application/pdf";
Response.BinaryWrite(buffer);
Response.End();
}
}
Note that I also added Response.End() to clear the buffer.
I have this code below which takes my GridView, populates it, and generates and opens an Excel file with the griddata in my browser.
What if I want to save that file directly to my server or attach it to an email message, instead of the display prompt that automatically pops up.
Can I do that with small modifications to the script?
protected void btnExcelExport_Click(object sender, EventArgs e)
{
HtmlForm form = new HtmlForm();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.AddHeader("content-disposition", string.Format("attachment;filename={0}", "Student.xls"));
Response.ContentType = "application/ms-excel";
StringWriter sw = new StringWriter();
HtmlTextWriter hw = new HtmlTextWriter(sw);
GridView1.AllowPaging = false;
BindGridDetails(GridView1);
form.Attributes["runat"] = "server";
form.Controls.Add(GridView1);
this.Controls.Add(form);
form.RenderControl(hw);
string style = #"<!--mce:2-->";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
you can save your grid data as a Comma Separated Value file on the server and email or save it directly on your server.
CSV files can be opened using Excel.
I am using the below code for export the data to excel sheet.
private void ExportToExcel(string fileName)
{
fileName = "MyXML.xls";
Response.Clear();
Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
Response.ContentType = "application/vnd.xls";
System.IO.StringWriter stringWrite = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
rptLinks.RenderControl(htmlWrite);
Response.Write(stringWrite.ToString());
Response.End();
}
Everything is working fine but when I try to open the excel file MyXML.xls by double clicking, a popup/dialog box open with the below message :
"The file you are trying to open , MyXML.xls is in different format than specified by the file extension. " etc..
Can we make some changes in code so that no popup/dialog should come?
Hope this helps
http://devblog.grinn.net/2008/06/file-you-are-trying-to-open-is-in.html
change Response.ContentType = "application/vnd.xls"; to Response.ContentType = "application/vnd.ms-excel"
I've a handler in asp.net app. When there comes some kind of request I want user to get download window, where I put PDF stream. I don't want PDF to be saved in memory.
I have the following code, but it fails to open, says pdf file was demaged and couldn't open it.
tell me other way to achieve my goal if you think mine is not good.
MemoryStream stream = new MemoryStream();
CreatePFD(T.Text, stream);
context.Response.Write(stream);
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("content-disposition", "attachment; filename=" + "Nots__Saved__FIle__fileName.pdf");
Now I have this code:
Document Doc = new Document(PageSize.A4, 80, 50, 30, 65);
System.IO.Stream outputStream = new System.IO.FileStream(#"C:\inetpub\wwwroot\c\wefwe.pdf", System.IO.FileMode.OpenOrCreate);
PdfWriter.GetInstance(Doc, outputStream);
Doc.Open();
List<IElement> htmlarraylist = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StringReader(T.Text), null);
for (int k = 0; k < htmlarraylist.Count; k++)
{
Doc.Add((IElement)htmlarraylist[k]);
}
outputStream.CopyTo(context.Response.OutputStream);
Doc.Close();
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("content-disposition", "attachment; filename=" + "Nots__Saved__FIle__fileName.pdf");
when i save pdf, the file is correct...
but when I get response the file is in correct. demaged...
You need to rewind the stream by setting stream.Position = 0.
Also, Response.Write(stream) will just print stream.ToString().
Instead, you should call stream.CopyTo(Response.OutputStream).