【问题标题】:.net core mvc get controller method return the downloading file , but not working?.net core mvc get controller 方法返回下载文件,但不起作用?
【发布时间】:2020-06-15 20:08:19
【问题描述】:

我有List<model>,我在 Javascript 中转换为 JSON,当我单击按钮时调用控制器方法 并像这样传递参数:

$('#exceldownload').click(function(){

    var json = @Html.Raw(Newtonsoft.Json.JsonConvert.SerializeObject(Model.ReportListModel,Newtonsoft.Json.Formatting.Indented));
    json = JSON.stringify(json);


    window.location = "@Url.Action("ReportExcel","Report")?model="+json+"";

});

和控制器代码:

public FileResult ReportExcel(string model)
        {
            var b = JsonConvert.DeserializeObject<List<ReportListModel>>(model);
            if (b.Count == 0)
            {
                return File(Encoding.UTF8.GetBytes("empty"), "text/plain", "empty");
            }
            else
            {
                DataTable table = (DataTable)JsonConvert.DeserializeObject(JsonConvert.SerializeObject(b), (typeof(DataTable)));

                using (var excelPack = new ExcelPackage())
                {
                    var ws = excelPack.Workbook.Worksheets.Add("WriteTest");
                    ws.Cells.LoadFromDataTable(table, true, OfficeOpenXml.Table.TableStyles.Light8);
                    var FileBytesArray = excelPack.GetAsByteArray();
                    return File(FileBytesArray, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "test.xlsx");
                }
            }
        }

但是当我点击按钮并变成这样时:

无法访问此网站, 本地主机拒绝连接, ERR_CONNECTION_CLOSED

我想当我点击按钮时下载excel文件。

【问题讨论】:

  • 我认为发送请求 url 错误

标签: javascript c# html model-view-controller


【解决方案1】:

尝试调试 ASP.NET 代码。可能发生内部服务器错误。

【讨论】:

  • 我尝试了调试模式控制器方法,但这种方法在调试模式下不起作用。当我单击按钮但从未进入方法时。
  • 好的,那么看起来该方法实际上从未被调用过。也许将 "@Url.Action("ReportExcel","Report")?model="+json+"" 更改为 '@Url.Action("ReportExcel","Report")?model='+json
【解决方案2】:

在这一行崩溃了:

window.location = "@Url.Action("ReportExcel","Report")?model="+json+"";

改成

window.location = @Url.Action("ReportExcel","Report") + "?model="+json+"";

【讨论】:

    猜你喜欢
    • 2020-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-16
    • 2018-04-08
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多