c# – 在ASP.NET MVC中从View传递模型到Controller
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 在ASP.NET MVC中从View传递模型到Controller,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2676字,纯文字阅读大概需要4分钟。
内容图文
![c# – 在ASP.NET MVC中从View传递模型到Controller](/upload/InfoBanner/zyjiaocheng/795/0a48433815b24974bb4c8bd9b55d19f5.jpg)
我正在研究我在ASP.NET MVC中的第一个应用程序,并且遇到了一个我无法弄清楚的障碍,即使在阅读整个互联网之后.
所以我有几个使用View Models创建的视图(它们是报告),它们是根据用户选择标准填充的.我正在尝试构建一个接受模型并以Excel格式导出它的方法(使用EPPlus),但模型需要从其中一个视图发送.这在某种程度上是功能/可用性,而不是技术要求.用户可以运行报告,查看报告后,可以单击按钮/链接,将创建他们正在查看的报告的Excel版本.我想传递正在显示的视图所基于的模型,因为已经完成了根据用户的报告选择标准构建此特定视图模型的工作.
这一切都很好,我可以成功地将一个模型从显示报告的视图传递给构建报告的方法. View Model I中的所有数据似乎都在那里,除了作为其一部分的Models(IEnumerable)集合. < - 那就是我被困住的地方. IEnumerable的集合在断点处有0个项目,但在创建视图模型并最初传递到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 })
并在控制器中
public void ExportExcel(int ID)
{
// Get your ReportViewModel based on the ID and do stuff
}
内容总结
以上是互联网集市为您收集整理的c# – 在ASP.NET MVC中从View传递模型到Controller全部内容,希望文章能够帮你解决c# – 在ASP.NET MVC中从View传递模型到Controller所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。