Reputation: 21849
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>
}
here is my model:
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; }
}
}
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 things. 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.
Upvotes: 0
Views: 132
Reputation: 830
Use this in your view should resolve the issue:
@model List<Customer>
Upvotes: 2
Reputation: 1186
You should change the definition of your model to have:
@model List<Customer>
@{
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>
}
Upvotes: 1
Reputation: 68685
Change your @model
to @model IEnumerable<Customer>
@model IEnumerable<Customer>
@{
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>
}
Upvotes: 1