剃刀功能:@helper和@functions有什么区别

时间:2018-02-08 09:01:26

标签: asp.net-mvc razor

关于asp.net mvc中的剃刀功能的几个问题。

1)见下面的代码

@helper WelcomeMessage(string username)
{
    <p>Welcome, @username.</p>
}

然后你这样调用它:@WelcomeMessage("John Smith")

@functions{
    public string GetSomeString(){
        return string.Empty;
    }
}
看到有两个剃刀功能。在一个@helper中用于声明剃刀功能,在第二个@functions中用于声明剃刀功能。那么告诉我@helper and @functions之间有什么区别?

2)我们可以在.cs代码中声明razor函数......如果是,那么我们需要遵循任何约定吗?

3)我们可以从剃刀函数

返回整数
@helper Calculator(int a, int b)
{
    @{
        var sum = a + b;
    }
    <b>@sum</b>
}

@Calculator(1, 2)

我们可以将总和返还给它的调用环境吗?

2 个答案:

答案 0 :(得分:3)

两者都是为了可重用性。

但是当没有html需要返回时我会使用@functions,我们只想做一些计算或一些业务逻辑,这意味着我们需要编写纯粹的 C#代码

对于@functions,当我们不想在视图中返回html时,我们可以使用它们。如果我们想要从@functions重新启动Html,我们需要从HtmlString而不是String专门返回@functions,对于HtmlString,我们还需要指定并包含命名空间如果我们想要返回@using System.Web.Mvc; @functions { public static HtmlString WelcomeMessage(string username) { return new HtmlString($"<p>Welcome, {username}.</p>"); } } ,请填写:

@helper

当我们想要创建html并使用一些逻辑渲染它时,@helper很有用,这意味着我们需要编写剃刀代码。

对于@helper{ public WelcomeMessage(string username) { <p>Welcome, @username.</p>; } } ,当我们定义的方法需要与Html混合并且我们想要返回一些html时,会使用它们。

when not defined(release):
  echo "Debug"

请阅读以下精彩文章,详细解释两者的不同之处:

https://www.mikesdotnetting.com/article/173/the-difference-between-helpers-and-functions-in-webmatrix

答案 1 :(得分:2)

您可以在一些静态助手类中将辅助代码放在cs中作为外部HTML助手:

public static class ExternalHelper
{
    public static MvcHtmlString Sum(this HtmlHelper htmlHelper, int[] items)
    {
        return new MvcHtmlString(items.ToArray<int>().Sum().ToString());
    }
}

并在View

中使用它
@Html.Sum(new int[] { 1, 3,7 })

编辑:不要忘记在Views / Web.config部分下放置该静态助手类命名空间

<add namespace="ProjectNamespace.Helpers" />
相关问题