Ben
Ben

Reputation: 2108

Generate file for download using Response.Write and change elements on the page

I am trying to change the text of a asp:textbox and collapse some ajaxToolkit:CollapsiblePanelExtenders within some ascx controls on my page as well as output a dynamically generated file. I have no problem collapsing the CollapsiblePanelExtenders and changing the text of the textbox from the codebehind or outputting a file. The problem arises when I want BOTH of these events to happen on the same postback. Unfortunately using Response.Write negates all of the other changes to the page.

Thanks in advance

Upvotes: 0

Views: 4027

Answers (1)

Nate Pinchot
Nate Pinchot

Reputation: 3318

Here is a quick concept example of how you could update text on the screen and download a file at the same time through an AJAX postback with an UpdatePanel.

ASPX code:

<asp:UpdatePanel id="update1" runat="server">
  <ContentTemplate>
    <asp:TextBox id="textbox1" runat="server" /><br />
    <asp:Button id="button1" onclick="button1_Click" runat="server" />
  </ContentTemplate>
</asp:UpdatePanel>

C# code:

private string GenerateDownloadLink(string fileContent, string fileName) {
  // worker process will need write access to this folder
  string downloadFolder = "./download";

  TextWriter file = new StreamWriter(Server.MapPath(downloadFolder) + @"\" + fileName);
  file.WriteLine(fileContent);
  file.Close();

  return downloadFolder + "/" + fileName;
}

private void button1_Click(object sender, EventArgs e) {
  textbox1.Text = "the file download will begin shortly...";

  string fileContent = "here is the content for a new dynamically generated file";

  string fileUrl = GenerateDownloadLink(fileContent, "hello.txt");

  ScriptManager.RegisterStartupScript(this, this.GetType(), "StartDownload", "window.location = '" + fileUrl + "';", true);
}

Also check out this MSDN example.

I would also like to add that UpdatePanels will eat your soul and you should get rid of them in favor of something like calling a WebMethod via AJAX if at all possible :)

Upvotes: 3

Related Questions