Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

foreach .. variables of type 'TodoTable' because 'TodoTable' does not contain a public instance or extension definition for 'GetEnumerator' Error

I have my View page below:

@model ToDoListApp.Models.TodoTable

@{
    ViewData["Title"] = "Urgent";
}

@foreach (var item in Model) {
    <p>@item.Id</p>
    <p>@item.Name</p>
}

Model:

namespace ToDoListApp.Models
{
    public partial class TodoTable
    {
        public int Id { get; set; }
        public string Name { get; set; } = null!;
        public bool Done { get; set; }
        public bool Urgent { get; set; }
    }
}

Controller:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[HttpGet]
public IActionResult Urgent(short id)
{
    var Task = db.TodoTables.SingleOrDefault(i => i.Id == id);
    return View("Urgent", Task);
}

But I am getting an error:

enter image description here

How I can solve the problem? Thanks for the help.

>Solution :

Solution for IEnumerable

Your ViewModel is not an IEnumerable and the foreach loop requires iterating an IEnumerable value.

Modify the @model as IEnumerable<ToDoListApp.Models.TodoTable> type:

@model IEnumerable<ToDoListApp.Models.TodoTable>

And make sure that your controller action returns the ViewModel as IEnumerable<ToDoListApp.Models.TodoTable> type.

[HttpGet]
public IActionResult Urgent(short id)
{
    IEnumerable<TodoTable> tasks = db.TodoTables
        .Where(i => i.Id == id)
        .ToList();

    return View("Urgent", tasks);
}

Solution for a single object

Seems your controller action returns a single object, then you shouldn’t use the foreach loop in the View.

@model ToDoListApp.Models.TodoTable

<p>@Model.Id</p>
<p>@Model.Name</p>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading