lundi 23 novembre 2015

Pass a List to View In MVC

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.

Aucun commentaire:

Enregistrer un commentaire