0

I have a ajax call to the controller to get the comma separated data in the following format,

public ActionResult GetSearchDataforDownloadtoCSV(string pSearchbykeyword, string pRequestCode)
{
   ReportsBE _lReportsBE = new ReportsBE();
   _lReportsBE.SearchKeyword = pSearchbykeyword;
   _lReportsBE.RequestCode = pRequestCode;

     List<ReportsBE> lstResult = new List<ReportsBE>();
     lstResult = _objReports.GetPackagelistAll_Search(_lReportsBE);

    StringBuilder sb = new StringBuilder();
    sb.Append("Request");
    sb.Append(",");
    sb.Append("Description");
    sb.Append("\n");

    foreach (var _RepBE in lstResult)
    {

        if (_RepBE.RequestCode != null)
        sb.Append(Escape(_RepBE.RequestCode));
        sb.Append(",");
        if (_RepBE.Description != null)
        sb.Append(Escape(_RepBE.Description));

        sb.Append("\n");
    }

return Json(sb.ToString());
}

This is my HTML,

@Html.LabelFor(model => model.SearchKeyword, "Search Packages by Keyword")
@Html.TextBoxFor(model => model.SearchKeyword, new { style = "width: 500px;" })

<button type="button" id="btnExport" onclick="DownloadCSV()" value="Export to CSV">Export to CSV</button>

This is my ajax call,

function DownloadCSV() {
        var _pSearchbykeyword = $('#SearchKeyword').val();
        var _pRequestCode = $('#RequestCode').val(); 

        var postData = {
            pSearchbykeyword: _pSearchbykeyword == '' ? '' : _pSearchbykeyword
            , pRequestCode: _pRequestCode == '' ? '' : _pRequestCode
        };

        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetSearchDataforDownloadtoCSV", "Reports")',
            data: postData,
            success: function (data) {
                if (data != null) {
                    // need to code here to through comma seperated data as csv file...
                }
            },
            error: function (xhr, ErrorText, thrownError) {
                alert("No Records Found!");

            }
        });

    }

My Problem is to download the comma separated string returned from controller as .csv file. Kindly help.

I tried to through the file like below,

var uri = 'data:text/csv;charset=utf-8,' + escape(data);
var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = "SearchList.csv";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);

This code is working in chrome but not in IE because of query string limitation. Any help would be really appreciated. thanks.

3 Answers 3

2

Don't use AJAX but a standard HTML <form>:

@using (Html.BeginForm("GetSearchDataforDownloadtoCSV", "Reports"))
{
    @Html.LabelFor(model => model.RequestCode, "Request Code")
    @Html.TextBoxFor(model => model.RequestCode, new { style = "width: 500px;" })


    @Html.LabelFor(model => model.SearchKeyword, "Search Packages by Keyword")
    @Html.TextBoxFor(model => model.SearchKeyword, new { style = "width: 500px;" })

    <button type="submit" value="Export to CSV">Export to CSV</button>
}

The reason you cannot download files using an AJAX request is because you have no way of showing the Save As dialog in javascript. So there's nothing you could do in your AJAX success callback to prompt the user to save the file. That's why the easiest solution is to use a standard form or anchor pointing directly to the controller action that will serve the CSV file.

Sign up to request clarification or add additional context in comments.

5 Comments

Thanks for the response. but in my form there are couple of buttons. One button is called "Search" it should display the result in grid. The other button is for exporting the result as csv. In this case how will I use standard HTML form? Pls help.
Then simply use javascript to submit the form when the corresponding button is clicked. Don't try any AJAX calls, it won't work.
What if my both buttons to be connected with different actionresult in controller. ex. for btnSubmit actionresult is "LoadGrid" and for btnDownload csv "DownlaodCSVData" is action result. Which means I cant simply post the form through js. I have to send parameters as well from the page. Can you guide me.. pls
You could leave the form action to the default submit button and when the user clicks on the export to CSV button in the corresponding javascript handler, you could set the form action before triggering the submit.
0

Personally, I would make use of the FileResult action type instead of the generic ActionResult method:

    public FileResult Download(long id)
    {
        var fileData = GetSearchDataforDownloadtoCSV(...);
        // use application/octet-stream for file downloads, saves us needing to
        // infer MIME type
        return File(fileData, "application/octet-stream", "Filename.csv");
    }

This way, you don't need to use AJAX at all.

Comments

0

This is how I solved as per Darin Dimitrov & Richard A. comments,

public FileResult GetSearchDataforDownloadtoCSV(string pSearchbykeyword, string pRequestCode)
{
   ReportsBE _lReportsBE = new ReportsBE();
   _lReportsBE.SearchKeyword = pSearchbykeyword;
   _lReportsBE.RequestCode = pRequestCode;

     List<ReportsBE> lstResult = new List<ReportsBE>();
     lstResult = _objReports.GetPackagelistAll_Search(_lReportsBE);

    StringBuilder sb = new StringBuilder();
    sb.Append("Request");
    sb.Append(",");
    sb.Append("Description");
    sb.Append("\n");

    foreach (var _RepBE in lstResult)
    {

        if (_RepBE.RequestCode != null)
        sb.Append(Escape(_RepBE.RequestCode));
        sb.Append(",");
        if (_RepBE.Description != null)
        sb.Append(Escape(_RepBE.Description));

        sb.Append("\n");
    }

byte[] buffer = System.Text.Encoding.UTF8.GetBytes(sb.ToString());
return File(buffer, "text/csv", "SearchList.csv");
}

And in my Javascript,

function DownloadCSV() {
        var _pSearchbykeyword = $('#SearchKeyword').val();
        var _pRequestCode = $('#RequestCode').val();

        pSearchbykeyword= _pSearchbykeyword == '' ? '' : _pSearchbykeyword;
        pRequestCode = _pRequestCode == '' ? '' : _pRequestCode;

        window.location = "Reports/GetSearchDataforDownloadtoCSV?pSearchbykeyword=" + pSearchbykeyword + "&pRequestCode=" + pRequestCode;
    }

This is working like a charm....:)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.