[英]How can we get the value from the async Action Method in c#
我有一個類似的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
獲取返回的值。
您需要更改方法以返回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));
}
然后,您需要聲明將結果存儲在操作外部的變量。 然后使用變量。
任務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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.