Wes Mes
Wes Mes

Reputation: 5

foreach statement cannot operate on variables of type 'Customers' because no a public instance definition for 'GetEnumerator'

I am trying to send a enumerable customer object in ViewResult to Index view of customers. but i am not able to use foreach with Model on the view page. The error associated with model says -

"foreach statement cannot operate on variables of type 'Customers' because 'Customers' does not contain a public instance definition for 'GetEnumerator'"

i tried to switch the code with an array but the problem remains

public class Customers
    {
        public int Id { get; set; }
        public string Name { get; set; }


    }

//Customer Controller
public class CustomersController : Controller
    {

        public IActionResult Index()
        {
            var customers = GetCustomers();
            return View(customers));
        }

        public IActionResult Details(int id)
        {
            var customer = GetCustomers().SingleOrDefault(c => c.Id == id);

            return View(customer);

        }

         private IEnumerable<Customers> GetCustomers()
         {
             var customer =  new List<Customers>
             {
                 new Customers { Id = 1, Name = "John Smith"},
                 new Customers { Id = 2, Name = "Mary Williams"}
             };

            return customer;
         }


    }

//View page Index

 @foreach (var customer in Model)
        {
            <tr>
                <td><a asp-area="" asp-controller="Customers" asp-action="Details">@customer.Name</a></td>
            </tr>
        }

The error displayed Under Model when the foreach statements executes, the it should output the name of the customers accordingly

Upvotes: 0

Views: 3109

Answers (1)

Backs
Backs

Reputation: 24913

In view you describe model as single object Customer.

Change your view:

@model IEnumerable<Vidly.Model.Customer>

Or:

@model List<Vidly.Model.Customer>

Upvotes: 1

Related Questions