-3

I am recreating the website NerdDinner using MVC, ASP.NET. I have created a database containing the dinners, their dates, and other related information. On my index View, I am attempting to use a foreach loop to list all the dinners to the screen. I keep getting the error:

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

    <ul>
    @foreach (var dinner in Model) 
    {

        <li>                 
            @dinner.Title           
            on 
            @dinner.EventDate.ToShortDateString()
            at
            @dinner.EventDate.ToShortTimeString()
        </li>
    }                    
    </ul>

I am pretty new to this and am not sure how to correct this issue, or really even WHERE the issue is located.

Here is my GitHub repo for the project. Sorry if the question is ambiguous, I am just a little lost and not really sure how to proceed from here.

3 Answers3

2

Your model is of the Type @model NerdDinner.Models.Dinner

So basically your Model is not a list. Changing your model to @model IEnumerable<NerdDinner.Models.Dinner> or @model List<NerdDinner.Models.Dinner> should fix your issue

edit: change Index.cshtml to

@model List<NerdDinner.Models.Dinner>

@{
ViewBag.Title = "Index";
}

<h2>Upcoming Dinners</h2>

<ul>

@foreach(var dinner in Model)
{
    <li>
        @dinner.Title
        on
        @dinner.EventDate.ToShortDateString()
        at
        @dinner.EventDate.ToShortDateString()
    </li>
}
</ul>
Nicolas Pierre
  • 1,174
  • 1
  • 21
  • 39
  • Ok, now this is where my genius is going to show. (sarcasm) So I figured something like this was the issue, but where do I make this change at? – Justin Mikesell Sep 08 '17 at 07:44
  • And don't worry, we all have been there, after a few years in programming now I still make mistakes that seems fairly simple – Nicolas Pierre Sep 08 '17 at 07:47
0
@foreach(var dinner in Model.dinners)
{
    <li>
        @dinner.Title
        on
        @dinner.EventDate.ToShortDateString()
        at
        @dinner.EventDate.ToShortDateString()
    </li>
}

Try this, you have to define which model you want to loop

0

In your view, the model needs to be an IEnumerablelike:

@model IEnumerable<NerdDinner.Models.Dinners>

and then you can use the foreachas below:

@foreach (var item in Model) {

//your code goes here..

}

Hope this helps.