Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 947
Mathletics Avatar asked May 04 '12 14:05

Mathletics


People also ask

How do I render a razor view to string?

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.

How can you comment using Razor syntax?

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 "//".

What is the Razor syntax in dotnet?

Razor is a markup syntax for embedding . NET based code into webpages. The Razor syntax consists of Razor markup, C#, and HTML.

What is Razor syntax MVC 5?

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.


2 Answers

Razor helpers return HelperResult objects.

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

For more information, see my blog post.

like image 118
SLaks Avatar answered Sep 20 '22 21:09

SLaks


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));

like image 45
Spikolynn Avatar answered Sep 18 '22 21:09

Spikolynn