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



关于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代码中声明剃须刀函数...如果是,那么我们需要遵循任何约定吗?

3(我们可以从剃须刀函数返回整数

@helper Calculator(int a, int b)
{
    @{
        var sum = a + b;
    }
    <b>@sum</b>
}
@Calculator(1, 2)

我们可以将总和返回其调用环境吗?

两者都是用于可重复使用的目的。

但是,当不需要返回HTML时,使用@functions,我们只想进行一些计算或一些业务逻辑,这意味着我们需要纯粹编写 c#code

对于@functions,当我们不想在视图中返回HTML时,我们可以使用它们。如果我们要从@functions进行REUTRN 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,当我们定义的方法与HTML混合时,使用它们时使用它们,我们希望返回一些HTML。

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

请阅读以下很棒的帖子,其中详细说明了两者的差异:

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

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

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

并在视图中使用它

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

编辑:不要忘记将该静态助手类名称空间放在视图/web.config部分

<add namespace="ProjectNamespace.Helpers" />

最新更新