c#异步-等待ToListAsync返回未定义

时间:2019-01-04 08:11:15

标签: json asp.net-mvc

public async Task<JsonResult> getEmployee(int roleId)
{
    var emp = await db.tbl_employee.Where(e => e.roleId == roleId).ToListAsync();
    return Json(emp, JsonRequestBehavior.AllowGet);
}

此操作返回未定义,但是如果我删除这样的等待

public async Task<JsonResult> getEmployee(int roleId)
{
    var emp = db.tbl_employee.Where(e => e.roleId == roleId).ToListAsync();
    return Json(emp, JsonRequestBehavior.AllowGet);
}

它将返回我想要的结果。我也尝试过从https://stackoverflow.com/a/25899982/9367841

public async Task<JsonResult> getEmployee(int roleId)
{
    var emp = await db.tbl_employee.Where(e => e.roleId == roleId).ToListAsync().ConfigureAwait(false);
    return Json(emp, JsonRequestBehavior.AllowGet);
}

但它不起作用。

2 个答案:

答案 0 :(得分:1)

我终于解决了。

如果您正在使用此操作

public async Task<JsonResult> getEmployee(int roleId)
{
    var emp = db.tbl_employee.Where(e => e.roleId == roleId).ToListAsync();
    return Json(emp, JsonRequestBehavior.AllowGet);
}

///我正在使用angularjs从服务器获取数据

$http.post("../controller/getEmployee", { roleId: id }).then(function (r) {
      console.log(r.data);
})

结果将是这样(来自console.log(r.data))

{Result: Array(1), Id: 50, Exception: null, Status: 5, IsCanceled: false, …}
AsyncState: null
CreationOptions: 0
Exception: null
Id: 50
IsCanceled: false
IsCompleted: true
IsFaulted: false
Result: [{…}]
Status: 5
__proto__: Object

获取员工列表。代替使用r.data,而使用r.data [“ Result”]。

$http.post("../controller/getEmployee", { roleId: id }).then(function (r) {
      $scope.list = r.data["Result"];
})

但是,如果您正在使用此操作

public async Task<JsonResult> getEmployee(int roleId)
{
    var emp = await db.tbl_employee.Where(e => e.roleId == roleId).ToListAsync();
    return Json(emp, JsonRequestBehavior.AllowGet);
}

您可以使用r.data获取员工列表。

$http.post("../controller/getEmployee", { roleId: id }).then(function (r) {
      $scope.list = r.data;
})

很抱歉,我没有显示如何获取数据,问题出在这里,而不是在服务器端。

答案 1 :(得分:0)

我想我已经看过这个了。你可以尝试以下吗?

public JsonResult getEmployee(int roleId)
{
    var emp = await db.tbl_employee.Where(e => e.roleId == roleId).ToListAsync();
    return Json(emp, JsonRequestBehavior.AllowGet);
}

ToListAsync返回Task<>

修改,请参见此处:Is it correct if i am using await + ToListAsync() over IQueryable which is not define as a task

相关问题