I am getting an error here in my razor view:
foreach statement cannot operate on variables of type 'Project.Model.ResultsClass' because 'Project.Model.ResultsClass' does not contain a public definition for 'GetEnumerator'
Here is my foreach
and how I am defining Model
@model Project.Models.ResultsClass
@foreach (var item in Model) {
}
Here is the controller method:
public ActionResult Results()
{
var results = db.Data.SqlQuery("SELECT * FROM Results").ToList();
ResultsClass result = new ResultsClass();
result.previewID = results[0].id;
result.dateSlot = results[0].dateSlot;
result.timeSlot = results[0].timeSlot;
result.startTime = results[0].startTime;
result.dateCreated = results[0].dateCreated;
return View(result);
}
And Here is my class:
public class ResultsClass
{
[DisplayName("Preview ID")]
public int previewID { get; set; }
[DisplayName("Date")]
public string dateSlot { get; set; }
[DisplayName("Time")]
public string timeSlot { get; set; }
[DisplayName("Start Time")]
public DateTime startTime { get; set; }
[DisplayName("Completed Time")]
public DateTime dateCreated { get; set; }
}
I don't understand what I am doing wrong?
You've passed the result
which is a type of ResultsClass
not a collection of ResultsClass
, and then attempt to iterate over it as if it were a collection so you can't use it in your foreach
loop. So in order to be able to use foreach
on it, you have to make it a collection. For example your foreach
loop works if you would passed results
instead of result
:
return View(results);
@model List<Project.Models.ResultsClass>
@foreach (var item in Model) {
}