【问题标题】:c# async - await ToListAsync returns undefinedc# async - await ToListAsync 返回 undefined
【发布时间】:2019-05-30 19:18:27
【问题描述】:
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);
}

但它不起作用。

【问题讨论】:

  • 什么是.ConfigureAwait(false),为什么需要它?
  • 不,我只尝试过 (stackoverflow.com/a/25899982/9367841),我认为它会解决我的问题,但它也返回 undefined。

标签: json asp.net-mvc


【解决方案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;
})

抱歉,我没有说明我是如何获取数据的,问题出在那里,而不是在服务器端。

【讨论】:

    【解决方案2】:

    我想我以前见过这个。请问可以试试下面的吗?

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

    ToListAsync 返回一个Task&lt;&gt;

    编辑见这里:Is it correct if i am using await + ToListAsync() over IQueryable which is not define as a task

    【讨论】:

    • 收到此错误“'await' 运算符只能在异步方法中使用。考虑使用 'async' 修饰符标记此方法并将其返回类型更改为 'Task'。” @scgough
    猜你喜欢
    • 2019-06-27
    • 2019-04-22
    • 2020-10-02
    • 1970-01-01
    • 2016-12-12
    • 1970-01-01
    • 1970-01-01
    • 2022-08-18
    • 1970-01-01
    相关资源
    最近更新 更多