I am trying to download an excel file from WEB API Get method of type HttpResponseMessage.
I am able to hit the method by making an AJAX call, the method also returns a resultcontent, but it's not downloading the file on the browser. I tried window.location, it redirects to a new page saying - 'The website cannot display the page'. I tried to debug by alerting in success & error, it alerts in error as [Object object]. Below is my code, please correct where I am going wrong. Thanks.
JavaScript
$(document).ready(function () {
$("#btnDownload").click(function () {
var apiUrl = "../api/DownloadExcel/ExportExcelFile?OriginalRequestNumber=";
var originalReqIdentifier = $('#OriginalRequestNumber').val();
$.ajax({
url: apiUrl + originalReqIdentifier,
type: 'GET',
dataType: 'json',
success: function (data) {
alert(data);
},
error: function (data) {
alert('hi');
}
});
});
});
HTML
<input href="#" class="btn" type="Submit" id="btnDownload" name="btnDownload" value="Download" />
c#
public class DownloadExcelController : ApiController
{
private IExcelExport _excelExport { get; set; }
public DownloadExcelController()
{
_excelExport = new GenerateExcel();
}
// GET api/DownloadExcel/ExportExcelFile
[HttpGet]
public HttpResponseMessage ExportExcelFile(string OriginalRequestNumber)
{
var ObjectToExcel = new List<DummyExternalLoginViewModel>
{
new DummyExternalLoginViewModel { Name = "Mohammed", FamilyName= "Ansari", State = "CA"},
new DummyExternalLoginViewModel { Name = "Harvey", FamilyName= "Spectre", State = "NY"},
new DummyExternalLoginViewModel { Name = "Mike", FamilyName= "Ross", State = "NY"},
new DummyExternalLoginViewModel { Name = "Donald", FamilyName= "Trump", State = "AL"},
new DummyExternalLoginViewModel { Name = "Spencer", FamilyName= "Mike", State = "AK"},
new DummyExternalLoginViewModel { Name = "Trump", FamilyName= "Donald", State = "AZ"},
new DummyExternalLoginViewModel { Name = "Bill", FamilyName= "Gates", State = "AR"}
};
var resultContent = _excelExport.Export(ObjectToExcel, "ExcelExport", true);
return resultContent;
}
}