我有一个async
方法,比如
[HttpPost]
public async Task<JsonResult> AddTwoIntegers(int param1, int param2)
{
var result = await (param1 + param2);
return Json(new {finalValue: result}, JsonRequestBehavior.AllowGet)
}
现在在另一个Action Method
我正在调用此函数
public ActionResult SomeFunction(string userSettingsViewModel)
{
Task<JsonResult> jsonData = this.AddTwoIntegers(5,10);
jsonData.ContinueWith(task =>
{
JsonResult result = task.Result;
if (result.Data.ToString() == "") {
var data = result.Data;
}
});
// I want to retrieve the value returned and use that value in some operation.
return Json("Success", JsonRequestBehavior.AllowGet);
}
如何从Action Result
获取返回值。
答案 0 :(得分:3)
您需要更改方法以返回Task<ActionResult>
并将其标记为async
,然后等待AddTwoIntegers()
的结果......
public async Task<ActionResult> SomeFunction(string userSettingsViewModel)
{
JsonResult result = await this.AddTwoIntegers(5, 10);
var jsonData = result.data;
// ...
return Json("Success", JsonRequestBehavior.AllowGet);
}
为了完整性,样本方法看起来应该是这样的......
[HttpPost]
public Task<JsonResult> AddTwoIntegers(int param1, int param2)
{
var result = param1 + param2;
return Task.FromResult(Json(new {finalValue: result},
JsonRequestBehavior.AllowGet));
}
答案 1 :(得分:2)
答案 2 :(得分:0)
然后,您需要声明将结果存储在操作之外的变量。然后使用变量。
任务jsonData = this.AddTwoIntegers(5,10);
Type data = null; //Note that I put Type because I don't know your type for result.Data
jsonData.ContinueWith(task =>
{
JsonResult result = task.Result;
if (result.Data.ToString() == "") {
data = result.Data;
}
});
// I want to retrieve the value returned and use that value in some operation.
//Now you can use your variable data here!!
return Json("Success", JsonRequestBehavior.AllowGet);
}