gpt4 book ai didi

c# - 在 ASP.NET MVC 中将模型从 View 传递到 Controller

转载 作者:太空狗 更新时间:2023-10-30 01:17:20 24 4
gpt4 key购买 nike

我正在使用 ASP.NET MVC 开发我的第一个应用程序,但遇到了一个我无法弄清楚的障碍,即使在阅读了整个互联网之后也是如此。

所以我有几个 View (它们是报告)是使用 View 模型创建的,这些 View 模型是根据用户选择标准填充的。我正在尝试构建一种接受模型并将其导出为 Excel 格式(使用 EPPlus)的方法,但需要从这些 View 之一发送模型。这在某种程度上是一种功能/可用性,而不是技术要求。用户可以运行报告,在查看报告后,可以单击按钮/链接,然后将创建他们正在查看的报告的 Excel 版本。我想传递正在显示的 View 所基于的模型,因为已经完成了根据用户的报告选择标准构建此特定 View 模型的工作。

一切都很好,我可以成功地将模型从显示报告的 View 传递到构建报告的方法。我传递的 View 模型中的所有数据似乎都在那里,除了作为其中一部分的模型集合 (IEnumerable)。 <--这就是我被困的地方。 IEnumerable 的集合在断点处有 0 个项目,但在最初创建 View 模型并将其传递到 View 时绝对不是这种情况。

我卡住了——请帮忙。

查看模型:

public class ReportViewModel
{

public int ProjectId { get; set; }

[Display(Name = "Project Name")]
public string ProjectName { get; set; }

[Display(Name = "Project #")]
public string ProjectNumber { get; set; }

public IEnumerable<SystemModel> SelectedSystems { get; set; }//has items when created and passed into the View intially, but not when the Model is passed from the View to the method/controller.

[Display(Name = "All Systems")]
public bool AllSystems { get; set; }

[Display(Name = "In Progress Systems")]
public bool InProgressSystems { get; set; }

[Display(Name = "Completed Systems")]
public bool CompletedSystems { get; set; }

[Display(Name = "Unchecked Systems")]
public bool UncheckedSystems { get; set; }

[Display(Name = "Systems with Problems - Ours")]
public bool JciIssue { get; set; }

[Display(Name = "Systems with Problems - Other's")]
public bool OtherIssue { get; set; }

[Display(Name = "Include Points with Problems")]
public bool IncludePoints { get; set; }

}

查看:

    @model ProjectOps_5.ViewModels.ReportViewModel


@{
ViewBag.Title = "Software Cx Status Report";
}

<h2>Software Cx Status Report</h2>

<div>
<div>
<hr />

@Html.ActionLink("Export to Excel", "ExportExcel", Model)//call to method

//the report

方法:

    public void ExportExcel(ReportViewModel model)
{
//make Excel file
}

最佳答案

您不能将包含复杂对象或集合属性的模型传递给 GET。 ActionLink() 方法在内部调用每个属性的 .ToString() 方法,所以基本上 DefaultModelBinder 试图将属性设置为如下所示

model.SelectedSystems = "System.Collections.Generic.IEnumerable<SystemModel>";

这当然会失败并且属性为 null

幸运的是它不起作用,否则你会生成一个非常难看的查询字符串,并且很容易超过查询字符串限制并抛出异常。

相反,传递 ProjectId 属性(我假设唯一标识对象)并在 ExportExcel() 方法中再次获取模型

@Html.ActionLink("Export to Excel", "ExportExcel", new { ID = Model.ProjectId })

在 Controller 中

public void ExportExcel(int ID)
{
// Get your ReportViewModel based on the ID and do stuff
}

关于c# - 在 ASP.NET MVC 中将模型从 View 传递到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32110271/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com