简体   繁体   中英

C# MVC Return problems(excel and view)

i'm having trouble with 2 things First: I have an a href with this function binded

$('#tblReports tbody').on('click', '.btnViewReportExcel', function (e) { 
            $.ajax({
                url: urlExcel,
                type: 'POST',
                data: {
                    initDate: initDate,
                    finalDate: finalDate
                }
            });
        });

And in the Controller i have this:

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult ComissionReport(DateTime initDate, DateTime finalDate)
        {
            var result = things to do;
            return View(result);
        }

My problem is the a href doesn't return the html loaded, return text in post How i return the reload of page with this data loaded?

And second problem is: I have this function, called by an a href too:

        [HttpPost]
        public ActionResult GenerateExcel(DateTime initDate, DateTime finalDate)
        {

                MemoryStream ms = data Generated by function

                if (ms != null)
                {
                    ms.Seek(0, SeekOrigin.Begin);
                    return File(ms, @"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml", "Test.xlsx");
                }
            return new EmptyResult();
        }

But the problem is the same thing as above, the post return the excel in text, and i want to return the download file

Anyone have the solution for this problems? Thanks for help, and sorry for my bad english

>> First: I have an a href with this function binded

Why ajax call? Rendered HTML returns as jqXHR and you can get this result this way,

var result = $.ajax(url: urlExcel ...

But I think its not that you except to get. You should simply do this to redirect:

window.location = urlExcel + "/" + you params here

or to get HTML content via AJAX

$.get(urlExcel, { param1: "value", ... } function(data) { alert(data); });

>> And second problem is: I have this function, called by an a href too

You should specify Content-Disposition header like 'attachment; filename="your file name"' to DOWNLOAD file without preview or anythig else, and you can use "application/octet-stream" for Content-Type header value.

Response.Headers.Add("Content-Disposition", "attachment ...));

return File(ms, ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM