1

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?

2 Answers 2

1

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);
            }
});
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.