Asp.net mvc 将模型数据传递给Url.Action方法
我在controller中有一个下载的ExcelList模型方法。我在查看页面中添加了一个链接Asp.net mvc 将模型数据传递给Url.Action方法,asp.net-mvc,Asp.net Mvc,我在controller中有一个下载的ExcelList模型方法。我在查看页面中添加了一个链接 @model IEnumerable<MyNameSpace.Models.Page> @if (Model != null) { if (Model.Count() != 0) { .... <div> <a href="@Url.Action("Dow
@model IEnumerable<MyNameSpace.Models.Page>
@if (Model != null)
{
if (Model.Count() != 0)
{
....
<div>
<a href="@Url.Action("DownloadExcel","Home", new {model=Model})">Download Excel</a>
</div>
}
}
controller:
public void DownloadExcel(List<Page> model)
{
var collection = model;
ExcelPackage Ep = new ExcelPackage();
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
ExcelWorksheet Sheet = Ep.Workbook.Worksheets.Add("Report");
Sheet.Cells["A1"].Value = "id";
Sheet.Cells["B1"].Value = "Name";
Sheet.Cells["C1"].Value = "Title";
Sheet.Cells["D1"].Value = "CreatedDate";
Sheet.Cells["E1"].Value = "CreatedBy";
int row = 2;
foreach (var item in collection)
{
Sheet.Cells[string.Format("A{0}", row)].Value = item.Id;
Sheet.Cells[string.Format("B{0}", row)].Value = item.Name;
Sheet.Cells[string.Format("C{0}", row)].Value = item.Title;
Sheet.Cells[string.Format("D{0}", row)].Value = Convert.ToDateTime(item.CreatedDate);
Sheet.Cells[string.Format("E{0}", row)].Value = item.CreatedBy;
row++;
}
Sheet.Cells["A:AZ"].AutoFitColumns();
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment: filename=" + "Report.xlsx");
Response.BinaryWrite(Ep.GetAsByteArray());
Response.End();
}
如何将模型数据从视图传递到控制器操作?它现在给了我一个空白的电子表格数据。谢谢在这种情况下,您不应该使用Url.Action。操作通常用于GET方法
在这种情况下,您可以使用ajax post作为
在cshtml中
<button onclick="download()">Download Excel</button>
在控制器中,将属性HttpPost添加为
谢谢我使用var collection=db.myTable.ToList测试了我的方法;我可以下载所有数据。因此,参数模型无法从视图接收模型存在问题。但当数据较大时,不能使用GET method尝试使用POST,调用DownloadExcel方法时出现GET 404错误。不知道为什么。在本地复制你的代码,在发布ajax时它能工作吗?复制了我的代码吗?JSON请求太大,无法反序列化。
function download() {
var obj= @Html.Raw(Json.Encode(Model));
$.ajax({
url: '@Url.Content("/Home/DownloadExcel")',
dataType: 'json',
type: 'POST',
data: JSON.stringify(obj),
contentType: 'application/json',
success: function (data) {
alert("success");
}
});
}
[HttpPost]
public void DownloadExcel(List<Page> model)