将列表传递给MVC中的视图 [英] Pass a List to View In MVC
问题描述
我将列表值传递给我的View。但我得到一个错误传入字典的模型项是'System.Collections.Generic.List'类型。这是我的控制器操作:
Hi,
I am passing a list values to my View. But I am getting an error of "The model item passed into the dictionary is of type 'System.Collections.Generic.List". Here is my controller action:
public ActionResult Index()
{
Test t = new Test();
List<Customer> myList= t.GetData();
return View(myList);
}
以下是视图:
Here is the view:
@model List<AsyncActions.Models.Test>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<table border="1" cellpadding="4">
@foreach (var row in Model)
{
<tr>
@*<td>@row."CustomerID"</td>
<td>@row."CustomerCode"</td>*@
</tr>
}
</table>
I已经尝试删除List<>从视图。当我这样做时,我收到一个错误,因为foreach语句不能对'AsyncActions.Models.Test'类型的变量进行操作,因为'AsyncActions.Models.Test'不包含'GetEnumerator'的公共定义。我试过这么多想法。我检查了这个链接,但这并没有解决我的问题。我无法找出我错过的东西。非常感谢任何帮助。
I have already tried removing List<> from view. When I do that, I am getting an error as "foreach statement cannot operate on variables of type 'AsyncActions.Models.Test' because 'AsyncActions.Models.Test' does not contain a public definition for 'GetEnumerator". I have tried so many thinks. I checked this link , but that didn't solved my issue. I am unable to find out what I have missed. Any help is much appreciated.
推荐答案
您的视图将此作为型号类型
Your view has this as the model type
@model List<AsyncActions.Models.Test>
但你传递的是模特
but you are passing this as the model
List<Customer>
视图中模型的类型必须与传递的内容相匹配,因此需要
The type of the model in your view has to match what is being passed so it needs to be
@model List<Customer>
你可能必须使用完整的客户类型名称,包括名称空间。
You might have to use the full Customer type name, including namespace.
如上面的答案所述,下面的行可以工作:
As mentioned in above answer, below line can work:
@model List<Customer>
更具体地说,它必须类似:
@model
IEnumerable或List或exact c你从行动中传递的ollection类型
<集合中类的完全限定名称或使用类名,顶部使用using语句>
如果您需要工作示例,请查看以下代码示例:
ASP.NET MVC 4 / MVC 5中视图中的多个模型 [ ^ ]
More specifically, it must be something like like:
@model
"IEnumerable or List or exact collection type which you are passing from action"
<"Fully qualified name of class in collection or use class name with using statement at top">
If you need working example, have a look at line, taken from code example given at:
Multiple Models in a View in ASP.NET MVC 4 / MVC 5[^]
@model IEnumerable <MultipleModelDemo.Models.Student>
谢谢。
Thanks.
@model IEnumerable<MvcApplication1.Models.Customer>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
<div>
<table border="1">
<tr>
<th>
CustomerCode
</th>
<th>
CustomerId
</th>
</tr>
@foreach (var row in Model)
{
<tr>
<th>@row.CustomerCode<br/></th>
<th>@row.CustomerId<br/></th>
</tr>
}
</table>
</div>
</body>
</html>
这篇关于将列表传递给MVC中的视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!