且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在ASP.NET MVC中将模型从View传递给控制器

更新时间:2023-02-25 19:10:22

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

You cannot pass a model that contains properties that are either complex objects or collections to a GET. Internally the ActionLink() method calls the .ToString() method of each property so basicaly the DefaultModelBinder is trying to set the property to as follows

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

哪个当然会失败,并且属性为 null .

which of course fails and the property is null.

幸运的是,它不起作用,否则您将生成一个非常丑陋的查询字符串,并且很容易超出查询字符串的限制并引发异常.

Fortunately it does not work, or you would generate a really ugly query string and could easily exceed the query string limit and throw an exception.

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

Instead, pass the ProjectId property (I'm assuming that uniquely identifies the object) and get the model again in the ExportExcel() method

@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
}