首页 > 解决方案 > .net core mvc get controller 方法返回下载文件,但不起作用?

问题描述

我有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");
                }
            }
        }

但是当我点击按钮并得到这样的:

无法访问此站点,Localhost 拒绝连接,ERR_CONNECTION_CLOSED

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

标签: javascriptc#htmlmodel-view-controller

解决方案


它在这一行崩溃:

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

将其更改为

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

推荐阅读