Mitchelln11
Active member
- Joined
- Apr 10, 2020
- Messages
- 39
- Programming Experience
- Beginner
How do you use a ForEach loop on ViewModels on .NET MVC?
I have 2 models:
A Park Model:
And A HikingTrail Model:
I wanted to use a ViewModel to access data from both of those 2 models. No matter which way I set up the ViewModel, I get errors.
This code gives me the following error:
I just want to loop through each HikingTrail on the Details view, which uses the ParkTrailViewModel
I've seen this error before as well, I just can't remember how I got it.
I have 2 models:
A Park Model:
C#:
public class Park
{
[Key]
public int ParkId { get; set; }
public string ParkName { get; set; }
public string ParkState { get; set; }
public string ParkLatitude { get; set; }
public string ParkLongitude { get; set; }
}
And A HikingTrail Model:
C#:
public class HikingTrail
{
[Key]
public int TrailId { get; set; }
public string TrailName { get; set; }
public string TrailDifficulty { get; set; }
public string TrailSummary { get; set; }
public double TrailLength { get; set; }
}
I wanted to use a ViewModel to access data from both of those 2 models. No matter which way I set up the ViewModel, I get errors.
C#:
public class ParkTrailViewModel
{
[Key]
public int ParkTrailId { get; set; }
[ForeignKey("Park")]
public int ParkId { get; set; }
public Park Park { get; set; }
[ForeignKey("HikingTrail")]
public int TrailId { get; set; }
public HikingTrail HikingTrail { get; set; }
}
This code gives me the following error:
The model item passed into the ViewDataDictionary is of type 'walkinthepark.Models.Park', but this ViewDataDictionary instance requires a model item of type 'walkinthepark.Models.ParkTrailViewModel'.
I just want to loop through each HikingTrail on the Details view, which uses the ParkTrailViewModel
C#:
@foreach (var item in Model.HikingTrail)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.TrailName)
</td>
<td>
@Html.DisplayFor(modelItem => item.TrailDifficulty)
</td>
<td>
@Html.DisplayFor(modelItem => item.TrailLength)
</td>
<td>
@Html.DisplayFor(modelItem => item.TrailCondition)
</td>
<td>
@Html.DisplayFor(modelItem => item.TrailSummary)
</td>
</tr>
}
I've seen this error before as well, I just can't remember how I got it.
CS1579 C# foreach statement cannot operate on variables of type because does not contain a public instance definition for 'GetEnumerator'