1

I have a helper method which retrieves data in a database asynchronously. The method works fine and is able to retrieve the data I need. Here is the method:

public static async Task<string> Translate(string word, string LanguageID,string token)
{
    if (!_HasLoadedTranslationList)
        _TranslationList = await GetTranslationList(token);

    foreach (TranslationDto translation in _TranslationList)
    {
        switch (LanguageID)
        {
            case "Chinese":
                if (translation.nameID.ToLower() == word.ToLower())
                {
                    return translation.Chinese;
                }
                break;
            case "English":
                if (translation.nameID.ToLower() == word.ToLower())
                {
                    return translation.nameID;
                }
                break;
            default:
                break;
        }
    }
    return null;
}

Now, this is initially called when rendering the View (using ASP.NET MVC btw):

<h1>@LanguageHelper.Translate("SIGN IN", @ViewBag.LanguageID,@ViewBag.Token)</h1>

However, instead of displaying the string, it displays

System.Threading.Tasks.Task`1[System.String]

How can I get the actual string value in the View?

g_b
  • 11,728
  • 9
  • 43
  • 80
  • 1
    Currently Razor views dont support asynchronous methods. Possible duplicate of http://stackoverflow.com/questions/24708805/cannot-return-value-from-async-method-in-view – Dandy Sep 09 '15 at 06:59
  • Following on from @Dandy 's comment - try changing your translate helper to be synchronous: `public static string Translate(string word, string LanguageID,string token)...`. I have a feeling this could be quite heavy on the database if there are a lot of translations being called. Have you thought about using `Resource` files to load in the translations? – scgough Sep 09 '15 at 07:24
  • 1
    You cant as per @Dandy but as per normal async you're getting back an awaitable (Task) (which you 're not awaiting) so your request is likely going to return before it's hit the db anyway which is why you're just getting the Type.ToString() being rendered in your view instead of some localized content. So even if/when you move this to your controller, you still need to await it. On top of that perf is going to be horrible. Either use resx files and/or some other cache. – rism Sep 09 '15 at 08:13

0 Answers0