我尝试使用以下ASP.NET MVC 4代码导出表(由jTable jquery插件生成,但它只是一个表,因此无关紧要)。它不会触发下载文件对话框。
另一个问题是虽然HTML编码表是由.ajax()POST发送的,但是当我尝试使用处理值时会触发错误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();
}
无法通过ajax调用实现文件下载响应,只有很少的方法可以实现此目的。以下是其中之一,
$("#exportToExcel").on("click", function (e) {
var form = $('form');
var input = $('<input type="hidden" name="input" value="" />');
input.val($(".jtable").html());
form.append(input);
form.attr('action', '/Reports/Export');
form.attr('method', 'POST');
form.submit();
})
希望这可以帮助。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句