Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cant get c# to make a downloadable csv

I am having to code up a button which, onclick, downloads a csv file onto the client's computer (this is a web app)

So, did some research, pulled all strings together, go figure, its not working.

I am trying to get this for now:

    protected void btnDownload_onClick(object sender, EventArgs e)
    {
        Response.Clear(); 
        Response.AddHeader("content-disposition", "attachment; filename=tmp.csv");
        Response.ContentType = "text/csv";
        Response.Write("one,two,three,four,five");
        Response.End();
    }

according to a blog that came up on google, that's all I need to get generate that csv an download it.

only, its not working and I cant figure out what's wrong with it.

1) firebug inspection: response is EMPTY.
2) VS Debugging, strangely stops after the line Response.End() and complaints that it cant find content.

Am I missing something? Thanks much. very much.

Edit: I just realized something, this is a child page and there is an update panel in the master page. Can this be the cause of the problem? if so, how can I cancel the ajax postback just for this child page?

like image 407
LocustHorde Avatar asked Jun 23 '11 17:06

LocustHorde


2 Answers

reading your comments and edit, looks like you want to cancel ajax postback for just this one button from child page and your update panel is in master page and you can't access it.

If I have that details correct, just add this code on your child content page's PageLoad():

        ScriptManager sm = ScriptManager.GetCurrent(Page);
        if (sm != null)
            sm.RegisterPostBackControl(btnDownload); 
        //btnDownload = the button ID, just copied from your code.

That will force full page postback and your files will be downloaded.

like image 73
iamserious Avatar answered Oct 08 '22 12:10

iamserious


I would prefer doing that on a WebHandler .ashx file. Separated from the main page you are at.

<%@ WebHandler Language="C#" Class="Handler" %>

using System;
using System.Web;

public class Handler : IHttpHandler
{
    public void ProcessRequest(HttpContext context)
    {
        context.Response.AddHeader("content-disposition", "attachment; filename=file.csv");
        context.Response.ContentType = "text/csv";
        context.Response.Write("1,2,3,4,5,6");
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }
}
like image 23
Michael D. Irizarry Avatar answered Oct 08 '22 12:10

Michael D. Irizarry