【发布时间】:2021-05-07 17:18:42
【问题描述】:
我在 asp.net core 3.1 中使用了没有异步方法的徽章,这是我的服务代码
public int GetNotSeenContact()
{
return _context.Contacts.Where(s => s.Seen == false).Count();
}
这是范围布局中的调用:
public int GetContactCont()
{
return _admin.GetNotSeenContact();
}
这是我使用它的地方:
int ConactBell = scope.GetContactCont();
这是我调用的 html 代码:
<span class="badge badge-pill badge-warning notification">@ConactBell</span>
这工作得很好,但是当我使用 Async 方法时,它会显示这个异常而不是用户的数字:
System.Runtime.CompilerServices.AsyncTaskMethodBuilder`1+AsyncStateMachineBox`1[System.Int32,DIG.Core.Classes.PanelLayoutScope+<GetContactCont>d__3]
现在这些是我在服务中的异步方法中的代码:
public async Task<int> GetNotSeenContact()
{
return await _context.Contacts.Where(s => s.Seen == false).CountAsync();
}
这是在我的作用域类中:
public async Task<int> GetContactCont()
{
return await _admin.GetNotSeenContact();
}
这是我在 html 代码中使用它的代码:
@inject PanelLayoutScope scope
@{
Task<int> ConactBell = scope.GetContactCont();}
我的html代码:
<span class="badge badge-pill badge-warning notification">@ConactBell</span>
请给我最好的解决方案,并告诉我为什么在我使用 Async 方法时会发生这种情况。非常感谢!
【问题讨论】:
-
这是控制器代码。不要把它放在视图中。这打破了 MVC 模式的工作方式——控制器完成繁重的工作并生成视图显示的视图模型/数据包。视图不支持异步代码,因为它不需要它 - 数据应该已经可用
-
即使你使用较新的 Razor Pages 模型,view 也不应该执行数据访问代码。这就是 Controller(在 MVC 中)或 PageModel(在 Razor Pages 中)的用途。
标签: asp.net-mvc asp.net-core bootstrap-4 asp.net-core-3.1 badge