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?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

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.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x