user2437588
user2437588

Reputation:

MVC, foreach statement cannot operate on variables of type because does not contain a public definition for 'GetEnumerator'

I am developing an application in .NET MVC and I am currently trying to pull a List of records from two tables(Models) and send the list to my view through a ViewModel. Below you can see my two original Models and the ViewModel

       public partial class Animal
{
    public int AnimalId { get; set; }
    public Nullable<int> UserId { get; set; }
    public string TagNo { get; set; }
    public Nullable<int> Species { get; set; }
    public Nullable<bool> Sex { get; set; }
    public Nullable<int> AnimalBreed { get; set; }
    public Nullable<System.DateTime> DOB { get; set; }
    public Nullable<int> OwnershipStatus { get; set; }
    public Nullable<System.DateTime> DateAdded { get; set; }
    public Nullable<bool> BornOnFarm { get; set; }

    public virtual Breed Breed { get; set; }
}



        public partial class Breed
{
    public int id { get; set; }
    public Nullable<int> SpeciesID { get; set; }
    public string Breed1 { get; set; }
}



        public partial class CowIndexVM
{

    public string TagNo { get; set; }
    public string AnimalBreed { get; set; }
    public Nullable<System.DateTime> DateAdded { get; set; }


}

Here you can see the code from the controller I am using to select a list of records which i will then display in a table in the view

     List <CowIndexVM> myCowIndexVM = (from animals in db.Animals
                                join aBreed in db.Breeds on animals.AnimalBreed equals aBreed.id
                                where animals.Species == 2 & animals.OwnershipStatus == 1
                                & animals.UserId == WebSecurity.CurrentUserId
                                orderby animals.DateAdded descending
                                select new CowIndexVM
                                {
                                    TagNo = animals.TagNo,
                                    AnimalBreed = aBreed.Breed1,
                                    DateAdded = animals.DateAdded
                                }).ToList();






        return View("Index", myCowIndexVM);

But when i try to run this I get the error shown above.

Can any one help me with it? Just to be clear I am trying to display the retrieved records in a table

Thanks

Upvotes: 0

Views: 1798

Answers (1)

user2437588
user2437588

Reputation:

I was able to find the cause of my problem.

At the top of my view where I declared what Model the view would take I had it declared as so:

    @Model FarmManager.ViewModels.CowIndexVM

I did not specify that the Model was of type IEnumerable. The following code did the trick

    @model IEnumerable<FarmManager.ViewModels.CowIndexVM>

Upvotes: 4

Related Questions