简体   繁体   中英

cannot return value from async method in view

I'm trying to return value from async html helper but it is giving following string instead of desired values.

"System.Threading.Tasks.Task+WhenAllPromise`1[System.Decimal]"

Method:

public async static Task<decimal> CalculateCurrency(this HtmlHelper helper, decimal amount, string from, string country)
    {
        if (await getValue(country))
        {
            string fromCurrency = string.IsNullOrEmpty(from) ? "USD" : from;
            string toCurrency = country;
            WebClient client = new WebClient();
            string url = string.Format("http://finance.yahoo.com/d/quotes.csv?e=.csv&f=sl1d1t1&s={0}{1}=X", fromCurrency.ToUpperInvariant(), toCurrency.ToUpperInvariant());
            Stream response = await client.OpenReadTaskAsync(url);
            StreamReader reader = new StreamReader(response);
            string yahooResponse = await reader.ReadLineAsync();
            response.Close();
            if (!string.IsNullOrWhiteSpace(yahooResponse))
            {
                string[] values = Regex.Split(yahooResponse, ",");
                if (values.Length > 0)
                {
                    decimal rate = System.Convert.ToDecimal(values[1]);
                    string res = string.Format("{0:0.00}", rate * amount);
                    return decimal.Parse(res);
                 }
            }
            return decimal.Zero;
        }
        return decimal.Zero;
    }

Call HTML Helper:

@Html.CalculateCurrency(22, "USD", "EUR")

Views don't support asynchronous methods. So as result you get result of default .ToString() function for type of result which indeed returns just type name.

Options:

  • move code to controller and call in from asynchronous top level (non-child) action with await . Pass data to view via model or ViewBag
  • convert to real synchronous code if you must call it from the view or child action
  • if not possible try .Result , but watch out for deadlocks. See await vs Task.Wait - Deadlock? for details/links.

Note: moving async code to child action will not help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM