【发布时间】:2016-02-25 12:14:49
【问题描述】:
我正在将一个列表值传递给我的视图。但是我收到“传递到字典中的模型项的类型为'System.Collections.Generic.List”的错误。这是我的控制器操作:
public ActionResult Index()
{
Test t = new Test();
List<Customer> myList= t.GetData();
return View(myList);
}
这里是视图:
@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>
}
这是我的模型:
namespace AsyncActions.Models
{
public class Test
{
public List<Customer> GetData()
{
try
{
Customer c = new Customer();
List<Customer> cst = new List<Customer>();
for (int i = 0; i < 10; i++)
{
c.CustomerID = i;
c.CustomerCode = "CST"+i;
cst.Add(c);
}
return cst;
}
catch (Exception)
{
throw new NotImplementedException();
}
}
}
public class Customer
{
public int CustomerID { get; set; }
public string CustomerCode { get; set; }
}
}
我已经尝试从视图中删除 List。当我这样做时,我收到一个错误,因为“foreach 语句无法对'AsyncActions.Models.Test' 类型的变量进行操作,因为'AsyncActions.Models.Test' 不包含'GetEnumerator”的公共定义。我已经尝试了很多东西。我检查了这个 link ,但这并没有解决我的问题。我无法找出我错过了什么。非常感谢任何帮助。
【问题讨论】:
-
看起来你还没有发布你的实际代码。 ` List
myList= t.GetData();` 表示您的模型是 List<Customer>。但是你的视图有别的东西作为模型。 -
@kosala 请查看更新后的问题。
-
我想你已经有了下面的答案。此评论与您的问题无关。您的模型中存在错误。您应该在 for 循环中定义
Customer c = new Customer();。 -
@kosala 是的,我已经得到了答案。非常感谢您找出错误。
标签: c# asp.net-mvc asp.net-mvc-3 model-view-controller view