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:
[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:
How I can solve the problem? Thanks for the help.
CodePudding user response:
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>