我尝试使用以下 ASP.NET MVC 4 代码导出表(由 jTable jquery 插件生成,但它只是一个表,因此无关紧要)。它不会触发下载文件对话框。
另一个问题是虽然 HTML 编码表是由 .ajax() POST 发送的,但当我尝试使用 .ajax() 处理值时会触发错误string inp = Request["input"];
。我[ValidateInput(false)]
在 [HttpPost] 之前和之后都使用了声明来克服“从客户端检测到潜在危险的 request.form 值”错误(因为我正在发送 HTML 表),但该声明不会阻止“一个潜在危险的 request.form 值......” 抛出异常 -
我的 .cshtml 页面中的代码
$("#exportToExcel").on("click", function (e) {
$.ajax({
url: '/Reports/Export',
cache: false,
dataType: "html",
type: 'POST',
data: { input: $(".jtable").html() },
success: function (data) {
},
complete: function () {
}
});
})
报告控制器中的代码:
[ValidateInput(false)]
[HttpPost]
public void Export()
{
//string inp = Request["input"];
string body = "<table><tr><td>2</td><td>3</td></tr><table>";
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=data.xls");
Response.Charset = "";
Response.Cache.SetCacheability(HttpCacheability.NoCache);
//Response.ContentType = "application/vnd.ms-excel";
Response.ContentType = "application/force-download";
Response.Write("<html xmlns:x=\"urn:schemas-microsoft-com:office:excel\">");
Response.Write("<head>");
Response.Write("<META http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">");
Response.Write("<!--[if gte mso 9]><xml>");
Response.Write("<x:ExcelWorkbook>");
Response.Write("<x:ExcelWorksheets>");
Response.Write("<x:ExcelWorksheet>");
Response.Write("<x:Name>Report Data</x:Name>");
Response.Write("<x:WorksheetOptions>");
Response.Write("<x:Print>");
Response.Write("<x:ValidPrinterInfo/>");
Response.Write("</x:Print>");
Response.Write("</x:WorksheetOptions>");
Response.Write("</x:ExcelWorksheet>");
Response.Write("</x:ExcelWorksheets>");
Response.Write("</x:ExcelWorkbook>");
Response.Write("</xml>");
Response.Write("<![endif]--> ");
Response.Write("<![endif]--> ");
Response.Write("</head>");
Response.Write("<body>");
Response.Write(body);
//Response.Write(inp);
Response.Write("</body>");
Response.Write("</html>");
Response.End();
}