Can I return a string using the @helper syntax in Razor?

Mathletics picture Mathletics · May 4, 2012 · Viewed 28.1k times · Source

I have a RazorHelpers.cshtml file in app_code which looks like:

@using Molecular.AdidasCoach.Library.GlobalConstants

@helper Translate(string key)
{
    @GlobalConfigs.GetTranslatedValue(key)
}

However, I have a case where I want to use the result as the link text in an @Html.ActionLink(...). I cannot cast the result to a string.

Is there any way to return plain strings from Razor helpers so that I can use them both in HTML and within an @Html helper?

Answer

SLaks picture SLaks · May 4, 2012

Razor helpers return HelperResult objects.

You can get the raw HTML by calling ToString().

For more information, see my blog post.