How I could pass a parameter to an CSV export method in MVC controller with Jquery/Ajax

448 Views Asked by At

On my view I have a button for export in CSV the current data view. This is a simple link to a method in the controller.

<input type="button" value="Exporter" id="btnexport" class="btnsearch" onclick="location.href='@Url.Action("ExportCSV", "AuditAddins")'" />

And the controller method

public void ExportCSV()
{
    auditAddins = AddinsCache.AuditAddinsCache;
    var sw = new StringWriter();
        sw.WriteLine(String.Format("{0};{1};{2};{3};{4}", "Date", "AddinName", "IsAddinActive", "UserName", "PcName"));
        foreach (var record in auditAddins)
        {
            sw.WriteLine(String.Format("{0};{1};{2};{3};{4}", record.Date, record.AddinList.AddinName, record.IsAddinActive, record.Users.UserName, record.Pc.PcName));
        }
        Response.Clear();
        Response.AddHeader("Content-Disposition", "attachment; filename=Export.csv");
        Response.ContentType = "text/csv";
        Response.Write(sw);
        Response.End();
}

It's working well. But I need to send a parameter to this method, because I have three design mode, and each have their own column order. So I have created a jquery/ajax script to send the paramater.

$("#btnexport").click(function () {
    var index = $('#CritID').find('option:selected').val();
    var d = { chx: index}
    $.ajax({
        url: "/AuditAddins/ExportCSV",
        type: "POST",
        data: d,
        success: function (data) {
            alert("Export ok !");
        },
    });
});

The main objective is to change the export method like that :

 public void ExportCSV(int chx)
    {
        ...
        switch (chx)
        {
            case 1:
                sw.WriteLine(String.Format("{0};{1};{2};{3};{4}", "Date", "AddinName", "IsAddinActive", "UserName", "PcName"));
                break;
            case 2:
                sw.WriteLine(String.Format("{0};{1};{2};{3};{4}", "Date", "UserName", "PcName","AddinName", "IsAddinActive"));
                break;
            ...
        }

The problem is that I don't have IE download window anymore. I have tried with actionresult method, it's doesn't work either.

1

There are 1 best solutions below

5
On

You don't have to use POST to send a parameter.

Instead, you can add a parameter to the GET request:

/AuditAddins/ExportCSV?index=2

and default to 1 if no parameter is provided.

To send multiple parameters, you can use & to separate them:

/AuditAddins/ExportCSV?index=2&param2=123

This should also solve the problem with the download window.