Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a Response.Write(...); in my Controller

I have a Controller with the following method:

public void ExportList()
{
    var out = GenExport();

    CsvExport<LiveViewListe> csv = new CsvExport<LiveViewListe>(out);
    Response.Write(csv.Export());
}

this should generate a csv file which the user can download.

I call this method via a jQuery request in my view:

$.getJSON('../Controller2/ExportList', function (data) {
    //...
});

the problem is, that I don't get any download and I don't know why. The method is called but without a download.

What is wrong here?

like image 413
gurehbgui Avatar asked Dec 06 '25 19:12

gurehbgui


1 Answers

Your controller methods need to always return an ActionResult. So the method should look more like

public ActionResult ExportList()
{
    var export = GenExport();

    CsvExport<LiveViewListe> csv = new CsvExport<LiveViewListe>(export);
    return new CsvResult(csv);
}

Where CsvResult is a class inheriting from ActionResult and doing the necessary to prompt the user for download of your Csv results.

For example, if you really need to Response.Write this could be:

public class CsvResult : ActionResult
{
    private CsvExport<LiveViewListe> data;
    public CsvResult (CsvExport<LiveViewListe> data)
    {
        this.data = data;
    }

    public override void ExecuteResult(ControllerContext context)
    {
        if (context == null)
        {
            throw new ArgumentNullException("context");
        }

        HttpResponseBase response = context.HttpContext.Response;

        response.ContentType = "text/csv";
        response.AddHeader("Content-Disposition", "attachment; filename=file.csv"));

        if (data!= null)
        {
            response.Write(data.Export());
        }
    }
}

You could also think about making this more generic, if your CsvExport class has the Export method:

public class CsvResult<T> : ActionResult
{

    private CsvExport<T> data;
    public CsvResult (CsvExport<T> data)
    {
        this.data = data;
    }

    .... same ExecuteResult code
}

Now it supports any of your csv downloads, not just LiveViewListe.

like image 66
Jamiec Avatar answered Dec 08 '25 07:12

Jamiec



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!