0

I have used badge in asp.net core 3.1 without Async method this is my code in service

 public int GetNotSeenContact()
    {
        return _context.Contacts.Where(s => s.Seen == false).Count();
    }

and this is call in scope layout :

 public int GetContactCont()
    {
        return _admin.GetNotSeenContact();
    }

and this is the place that I use this:

 int ConactBell = scope.GetContactCont();

and this is my html code that I called :

 <span class="badge badge-pill badge-warning notification">@ConactBell</span>

this is working very well but when I make it with Async method, it shows this exception instead of number for user:

System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Int32,DIG.Core.Classes.PanelLayoutScope+&lt;GetContactCont&gt;d__3]

Now these are my codes in async method in service:

 public async Task<int> GetNotSeenContact()
    {
        return await _context.Contacts.Where(s => s.Seen == false).CountAsync();
    }

this is in my scope class:

 public async Task<int> GetContactCont()
    {
        return await _admin.GetNotSeenContact();
    }

and this is the code where I use it inside html code:

@inject PanelLayoutScope scope
@{
Task<int> ConactBell = scope.GetContactCont();}

my html code :

<span class="badge badge-pill badge-warning notification">@ConactBell</span>

Please give me the best solution and tell me why does this happen when I use Async method. Thank you so much!

Yiyi You
  • 16,875
  • 1
  • 10
  • 22
  • 3
    That's controller code. Don't put it in the view. That breaks how the MVC pattern works - the controller does the heavy lifting and produces a viewmodel/bag of data that's displayed by the view. A view doesn't support async code because it *doesn't need it* - the data should already be available – Panagiotis Kanavos Feb 03 '21 at 13:06
  • 3
    Even if you use the newer Razor Pages model, the *view* should never execute data access code. That's what the Controller (in MVC) or the PageModel (in Razor Pages) is for. – Panagiotis Kanavos Feb 03 '21 at 13:08

1 Answers1

1

Because the method is asynchronous,you can try to use await.Change

@{
Task<int> ConactBell = scope.GetContactCont();}

to

@{
    var ConactBell =await scope.GetContactCont();}

result:

enter image description here

Yiyi You
  • 16,875
  • 1
  • 10
  • 22