Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle FileStream return type in .ajax post?

I am sending JSON object through following code.. Controller returning values in CSV format that should be provide promt to open or save as CSV file. I unable to understand that what exactly code should be write in success: function (result)

Link for Export

Html.ActionLink("Export", "", "", null, new { @onclick = "return exportData();"})

function exportData() {

var searchViewModel = getExLogSearchModelData();
var path = getAbsolutePath("ExclusionLog", "ExportData");
$.ajax({
    url: path,
    cache: false,
    contentType: 'application/json; charset=utf-8',
    dataType: 'html',
    type: 'POST',
    data: JSON.stringify(searchViewModel),
    success: function (result) {
    },
    error: function (error) {
        $("#voidcontainer").html("Error");
    }
});

}

Controller ActionResult

    public ActionResult ExportData(ExclusionLogSearchViewModel postSearchViewModel)
    {
        try
        {
            IEnumerable<ExclusionLogViewModel> exclusionLogData = null;
            exclusionLogcData = this._workerService.GetExclusionLogData(postSearchViewModel);

            return CSVFile(exclusionLogMembershipSyncData.GetStream<ExclusionLogViewModel>(), "ExclusionLogTables.Csv");
        }
        catch (Exception ex)
        {
                throw ex;
        }
        return null;
    }

Can you please suggest how to do this?

like image 417
Pradeeepk Avatar asked Oct 21 '22 20:10

Pradeeepk


1 Answers

I've hit the same problem and I didn't find a way to download file using $.ajax but I found an excellent JavaScript library that provides similar behavior:

https://github.com/johnculviner/jquery.fileDownload

You just need to invoke something like this:

$.fileDownload(path, {
    httpMethod: 'POST',
    data: JSON.stringify(searchViewModel),
    success: function (result) {
    },
    error: function (error) {
        $("#voidcontainer").html("Error");
    }
});

And remember to create cookie in controller. In src/Common there is suitable action filter that do it for you.

like image 113
Sławomir Rosiek Avatar answered Oct 25 '22 18:10

Sławomir Rosiek