0

I am building a ToDo list app with ASP.NET Core Razor Pages and I am using EF Core.

I have a model that is ToDo

public class ToDo
{
    public int Id { get; set; }
    public string Title { get; set; }
    public bool IsCompleted { get; set; }
}

Heres PageModel:

public class IndexModel : PageModel
{
    public IEnumerable<ToDo> ToDos { get; set; }

    // constructor and DI code omitted 

    public async void OnGet()
    {
        ToDos = await _context.ToDos.ToListAsync();
    }
}

Here's razor page that uses this:

@page
@model IndexModel
@{
    Layout = "_Layout";
}

<div>
    @foreach(var todo in Model.ToDos)
     {
        <h4>@todo.Title</h4>
        <p>Is Completed: @(todo.IsCompleted ? "Yes" : "No")</p>
     }
</div>

When I visit this page I get System.NullReferenceException at Model.ToDos

However, when I change OnGet method to use ToList() instead:

public void OnGet()
{
    ToDos = _context.ToDos.ToList();
}

Everything works perfectly.

Why can't I use ToListAsync()

uvr
  • 515
  • 4
  • 12
abcDE
  • 63
  • 1
  • 7

1 Answers1

0

Have you tried this?

    public async Task OnGetAsync()
    {
        ToDos = await _context.ToDos.ToListAsync();
    }
zAnthony
  • 332
  • 4
  • 17
  • this actually works ! Can you please explain why my approach is wrong and this approch is correct. I am new to C#. – abcDE Apr 27 '21 at 14:30
  • https://learn.microsoft.com/en-us/archive/msdn-magazine/2013/march/async-await-best-practices-in-asynchronous-programming#avoid-async-void – phuzi Apr 27 '21 at 15:00
  • Like @phuzi link. Async and Await is quite a big topic. My personal rule is that any method that is calling an async method should be an async method and the return type should be Task or Task where return type can be a string, int, object and etc. You should always await your async method unless you intend to call an async method and do something else and later in the code await the result. Please youtube a few video's on "async await c#" to have a better understanding. – zAnthony Apr 27 '21 at 18:10