【发布时间】:2015-03-09 16:47:28
【问题描述】:
这让我发疯了。我有一个页面,我需要在其中向控制器发布 JSON,它将对其进行处理并返回一个 Excel 文件以供下载。到目前为止,它似乎运行正常,但是当它返回到 ajax 调用时,我收到一个解析器错误和消息“意外的令牌 P”。我已经尝试了很多不同的配置和调用方法(标准 MVC ActionRequest 到 WebApi 帖子),但它们都没有改变。这是我正在运行的代码。
JavaScript:
var treatmentplan = {"PlanRecordStatusId":"1","PlanRecordDateBegin":"","PlanRecordDateEnd":"","ClientClaimNumber":"","PatientNumber":0,"requestAction":3};
$.ajax({
//global: true,
//url: '/home/ExcelRpt',
url: '/api/TreatmentPlanExcel',
type: 'POST',
dataType: 'json',
data: treatmentplan,
//contentType: 'application/json; charset=utf-8',
success: function (data) {
//var msg = data.Message;
//$('#results').html(msg);
$("#tmpFrame").attr('src', 'URL-TO-EXCEL-FILE');
}
, error: function (jqXHR, exception, error) {
if (jqXHR.status === 0) {
alert('Not connect.n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.n' + jqXHR.responseText);
}
$('#log').html(error.message);
}
});
这是 C# 代码(WebApi 和 MVC 控制器版本),我不打算包含我的 ToExcel 扩展,我知道这部分有效,只是在返回时下载它。它正在到达此代码,生成数据并返回。我只需要看看到底发生了什么。如果有首选的调用方式,也请告诉我(WebApi 或 MVC)
C#
Web API 版本
public HttpResponseMessage Post(TreatmentPlanRequest tpRequest) {
tpRequest.Verify();
List<TreatmentPlan> tpl = DataAccess.GetReportDap(tpRequest).ToList();
HttpResponseMessage result = new HttpResponseMessage(HttpStatusCode.OK);
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var package = tpl.ToExcel("TreatmentReport");
var fileStream = new MemoryStream();
package.SaveAs(fileStream);
fileStream.Position = 0;
result.Content = new StreamContent(fileStream);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
return result;
}
这是 MVC 控制器版本
[HttpPost]
public ActionResult ExcelRpt(TreatmentPlanRequest tpRequest) {
tpRequest.Verify();
List<TreatmentPlan> tpl = DataAccess.GetReportDap(tpRequest).ToList();
var contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
var package = tpl.ToExcel("TreatmentReport");
var fileStream = new MemoryStream();
package.SaveAs(fileStream);
fileStream.Position = 0;
var fsr = new FileStreamResult(fileStream, contentType);
fsr.FileDownloadName = "TreatmentReport";
return fsr;
}
从这里开始,我不知道为什么这不起作用。我在谷歌上搜索了如何在 MVC 中执行此操作(我曾经使用 Web 表单执行此操作并且从未遇到过问题)。我猜我的问题是在退货或
【问题讨论】:
标签: c# ajax json excel model-view-controller