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?
Listing 1: Rendering a Razor View to String from within a Controller. The RenderViewToString() method works by receiving a controller context and virtual view path (i.e., ~/views/item/page. cshtml ) and optional model data that are passed to the view.
Comments Razor View Engine has two types of comments, one is single-line and another is multiline. Razor uses the syntax "@* .. *@" for the comment block but in a C# code block we can also use "/* */" or "//".
Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML.
ASP.NET MVC 5 for Beginners Razor is a markup syntax that lets you embed server-based code into web pages using C# and VB.Net. It is not a programming language. It is a server side markup language. Razor has no ties to ASP.NET MVC because Razor is a general-purpose templating engine.
Razor helpers return HelperResult
objects.
You can get the raw HTML by calling ToString()
.
For more information, see my blog post.
I don't think there is a way to make @helper
return other types than HelperResult
. But you could use a function with a return type of string
, e.g.
@functions { public static string tr(string key) { return GlobalConfigs.GetTranslatedValue(key); } }
then
@Html.ActionLink(tr("KEY"), "action", "controller")
See also http://www.mikesdotnetting.com/article/173/the-difference-between-helpers-and-functions-in-webmatrix
edit: MVC Razor: Helper result in html.actionlink suggests your helper can return a string by using @Html.Raw(GlobalConfigs.GetTranslatedValue(key));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With