循环类型为“System.Threading.Tasks.Task

本文关键字:System Task Collections Generic Tasks Threading 类型 循环 循环类 | 更新日期: 2023-09-27 18:31:09

在带有SignalR的 Asp.Net 项目MVC中,我正在尝试迭代Javascript客户端中Service返回的对象。我收到以下代码中存在的foreach语句的编译错误

foreach 语句不能对类型为"System.Threading.Tasks.Task>"

的变量进行操作,因为"System.Threading.Tasks.Task>"不包含"GetEnumerator"的公共定义

有人可以建议应该在视图/服务呼叫中进行哪些更改吗?

查看代码

  @model  System.Threading.Tasks.Task<List<JobCurrentStatusDetails>>
   <script type="text/javascript">

                var connection = $.hubConnection();
                var hub = connection.createHubProxy("JobDetailsHub");
                hub.on('updateData',function(jSonRefreshData){
                    console.log(jSonRefreshData);
                });
                hub.invoke('NotifyUpdates').done(function(jSonRefreshData){
                    @Model = jSonRefreshData
                    @{int countTiles = 0;}
                    @foreach(item in Model)
                    {
                        if(item.color == "red")
                        {}
                         if(item.color == "green")
                         {}
  }
                });
    </script>

添加服务器端代码

 public async Task<List<JobCurrentStatusDetails>> NotifyUpdates()
        {
       var hubContext = lobalHost.ConnectionManager.GetHubContext<JobDetailsHub>    ();
       if (hubContext != null)
       {
           db =  DataAccess.DataAccessModels.GetDashboardCounts();
           return await hubContext.Clients.All.updateData(db);
       }
       else return null;
   }

控制器代码如下:

public  ActionResult Index()
        {
            DataAccess da = new DataAccess();
            var jobDetailService = new JobDetailsService(da);
            return View(jobDetailService.NotifyUpdates());

        }

循环类型为“System.Threading.Tasks.Task<System.Collections.Generic

您返回的任务作为模型。您可以改为这样做:

public List<JobCurrentStatusDetails> NotifyUpdates()
{
   var hubContext = lobalHost.ConnectionManager.GetHubContext<JobDetailsHub>();
   if (hubContext != null)
   {
       db =  DataAccess.DataAccessModels.GetDashboardCounts();
       return hubContext.Clients.All.updateData(db).Result;
   }
   else return null;
}