string 我可以在 Razor 中使用 @helper 语法返回一个字符串吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10451036/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Can I return a string using the @helper syntax in Razor?
提问by Mathletics
I have a RazorHelpers.cshtml file in app_code
which looks like:
我有一个 RazorHelpers.cshtml 文件,app_code
其中如下所示:
@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.
但是,我有一个案例,我想将结果用作@Html.ActionLink(...)
. 我无法将结果转换为字符串。
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?
有什么方法可以从 Razor 助手返回纯字符串,以便我可以在 HTML 和@Html
助手中使用它们?
回答by SLaks
Razor helpers return HelperResult
objects.
Razor 助手返回HelperResult
对象。
You can get the raw HTML by calling ToString()
.
您可以通过调用获取原始 HTML ToString()
。
For more information, see my blog post.
有关更多信息,请参阅我的博客文章。
回答by Leniel Maccaferri
In your case, I think this would also work:
在你的情况下,我认为这也适用:
@(GlobalConfigs.GetTranslatedValue(key))
Additional sample:
附加示例:
@helper GetTooltipContent()
{
if(Model.SubCategoryType == SUBCATTYPE.NUMBER_RANGE)
{
@(string.Format("{0} to {1}", Model.SubCategoryMinimum, Model.SubCategoryMaximum))
}
else if(Model.SubCategoryType == SUBCATTYPE.NUMBER_MAXIMUM)
{
@("<= " + Model.SubCategoryMaximum)
}
else if(Model.SubCategoryType == SUBCATTYPE.NUMBER_MINIMUM)
{
@(">= " + Model.SubCategoryMinimum)
}
}
回答by Spikolynn
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.
我认为没有办法让@helper
返回其他类型而不是HelperResult
. 但是您可以使用返回类型为 的函数string
,例如
@functions {
public static string tr(string key) {
return GlobalConfigs.GetTranslatedValue(key);
}
}
then
然后
@Html.ActionLink(tr("KEY"), "action", "controller")
@Html.ActionLink(tr("KEY"), "action", "controller")
See also http://www.mikesdotnetting.com/article/173/the-difference-between-helpers-and-functions-in-webmatrix
另见http://www.mikesdotnetting.com/article/173/the-difference-between-helpers-and-functions-in-webmatrix
edit: MVC Razor: Helper result in html.actionlinksuggests your helper canreturn a string by using @Html.Raw(GlobalConfigs.GetTranslatedValue(key));
编辑:MVC Razor: Helper result in html.actionlink建议你的助手可以通过使用返回一个字符串@Html.Raw(GlobalConfigs.GetTranslatedValue(key));
回答by MatrixRonny
The following statements have been validated against MVC version 5.2.4.0
. I am mostly targeting the part with: 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?
以下语句已针对 MVC 版本进行了验证5.2.4.0
。我主要针对以下部分:有没有办法从 Razor 助手返回纯字符串,以便我可以在 HTML 和 @Html 助手中使用它们?
I did some research on how the built in MVC helpers work and they are actually properties of System.Web.Mvc.WebViewPage
class, so they have nothing to do with @helper
feature.
我对内置的 MVC 助手如何工作进行了一些研究,它们实际上是System.Web.Mvc.WebViewPage
类的属性,因此它们与@helper
功能无关。
Any @helper
encodes strings as HTML and works as if the code is copy pasted to the View inside a Razor code block, aka @{ code }
. On the other side, @functions
are supposed to be used inside Razor blocks.
Any@helper
将字符串编码为 HTML,就像将代码复制粘贴到 Razor 代码块(又名@{ code }
. 另一方面,@functions
应该在 Razor 块内使用。
Well, if a @helper
works as if the code is copy pasted, why not use @Html.Raw("<p>cool</p>")
? Because the Html property is null inside helpers. Why? I have no idea.
好吧,如果 a@helper
就像代码被复制粘贴一样工作,为什么不使用@Html.Raw("<p>cool</p>")
?因为 Html 属性在 helper 中为 null。为什么?我不知道。
Ok, but we can use a function to return a string and then apply @Html.Raw
on the result. Does that work? Yes, it does. The following example creates a <p>
element in the DOM:
好的,但是我们可以使用一个函数来返回一个字符串,然后应用@Html.Raw
到结果上。那样有用吗?是的,它确实。以下示例<p>
在 DOM 中创建一个元素:
@functions
{
static string GetString()
{
return "<p>awesome</p>";
}
}
@Html.Raw(GetString())
If you don't understand why @Html.Raw
is necessary, please read this fine article from @SLaks about Razor automatic HTML encoding.
如果您不明白为什么@Html.Raw
有必要,请阅读来自 @SLaks 的这篇关于Razor 自动 HTML 编码的精美文章。
What about the approach with the built in properties? Yes, it is possible to create static classes with public methods that work just like that. The only problem is that you have to include the namespace in the View, with the @using
keyword. Can that be improved? Yes, by adding the namespace in the Web.config
within the Views folder. Example:
内置属性的方法呢?是的,可以使用像这样工作的公共方法来创建静态类。唯一的问题是您必须使用@using
关键字在视图中包含名称空间。可以改善吗?是的,通过Web.config
在 Views 文件夹中添加命名空间。例子:
Helpers/Global.cs
助手/Global.cs
namespace WebApp.Helpers
{
public static class Global
{
public static IHtmlString GetString()
{
return new HtmlString("Something <b>cool</b>");
}
}
}
Views/Web.config
视图/Web.config
<?xml version="1.0"?>
<configuration>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.4.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<!-- Add to the end of namespaces tag. -->
<add namespace="WebApp.Helpers" />
Usage
用法
@Global.GetString()
What is the outcome? The text Something
and an additional <b>
element will be found in the DOM. If you need access to the Request
, simply add an HttpContextBase
parameter to the helper method and pass the WebViewPage.Context
property when calling it.
结果如何?文本Something
和附加<b>
元素将在 DOM 中找到。如果您需要访问Request
,只需HttpContextBase
向辅助方法添加一个参数并WebViewPage.Context
在调用它时传递属性即可。
Can it get better? Yes, as always. The same output can be created with @helper
and @functions
:
能好起来吗?是的,一如既往。可以使用@helper
和创建相同的输出@functions
:
@helper GetString1()
{
@(new HtmlString("Something <b>awesome</b>"))
}
@functions {
public static IHtmlString GetString2()
{
return new HtmlString("Something <b>awesome</b>");
}
}
@MyHelper.GetString1()
@MyHelper.GetString2()
Answer
回答
Regarding OP's question, I recommend @Spikolynn's approach to create a function that returns string
. However, if you need to write many lines of C# code in the helper, I suggest using a static class helper.
关于 OP 的问题,我推荐 @Spikolynn 的方法来创建一个返回string
. 但是,如果您需要在帮助器中编写多行 C# 代码,我建议使用静态类帮助器。