Reputation: 5941
i have application where user can download excel report using this button:
<a href="@Url.Action("GetYearlyReport", new {@ViewBag.plantId})" class="excelIcon" title="Get Yearly Report"></a>
my method looks following:
[HttpPost]
public ActionResult GetYearlyReport(int plantId)
{
string fileName = Reports.GenerateYearlyReport();
if (!String.IsNullOrEmpty(fileName))
{
byte[] fileBytes = GetFile(fileName);
return File(fileBytes, MediaTypeNames.Application.Octet, fileName);
}
return Json(new { Result = "ERROR", Message = "Missing some parameters." });
}
Now , wheren filename isn't empty then i got the file, but when it is then i am redirected to non existed page GetYearlyReport, while I would like to just say message from json, is that possbile?
Upvotes: 1
Views: 1175
Reputation: 2590
Your code seems fine, I believe redirection is occurred in the Reports.GenerateYearlyReport
method, there must be a way to check the result of the method before invoke it.
Upvotes: 1
Reputation: 17492
Why not just add another if()
statement to handle the scenarios where file names are empty, and return an error and handle it client side?
$.ajax({
url: 'xxx/GetYearlyReport',
data: { plantId: plantId},
type: 'POST',
error: function (xhr, textStatus, exceptionThrown) {
if (xhr.status == xxx) {
alert(xhr.responseText);
}
},
success: function (data) {
if(data.Result = 'ERROR'){
//do something
alert(data.Message);
}
}
});
Or better define a common error handler for your ajax calls?
$(document).ajaxError(function (e, xhr, settings) {
if (xhr.status == 401)
{
alert("unauthorized");
}
else if (xhr.status == 0) {
alert(' Check Your Network.');
} else if (xhr.status == 404) {
alert('The resource you are looking for can not be found.');
} else if (xhr.status == 500) {
alert('Internel Server Error.');
} else {
alert('Unknow Error.\n' + x.responseText);
}
});
Upvotes: 1