关于asp.net mvc 中剃刀功能的几个问题。
1)看下面的代码
@helper WelcomeMessage(string username)
{
<p>Welcome, @username.</p>
}
Run Code Online (Sandbox Code Playgroud)
然后你像这样调用它: @WelcomeMessage("John Smith")
@functions{
public string GetSomeString(){
return string.Empty;
}
}
Run Code Online (Sandbox Code Playgroud)
看到有两个剃刀功能。第一个@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)
Run Code Online (Sandbox Code Playgroud)
我们可以将 sum 返回到它的调用环境吗?
两者都是为了可重用性。
但是@functions当不需要返回html并且我们只想做一些计算或一些业务逻辑时使用,这意味着我们需要编写纯C#代码。
因为@functions当我们不想在视图中返回 html 时,我们可以使用它们。如果我们想从 返回 Html,@functions我们需要专门HtmlString从它返回而不是String因为@functions我们还需要指定并在其中包含命名空间,如果我们想返回HtmlString如下:
@using System.Web.Mvc;
@functions {
public static HtmlString WelcomeMessage(string username)
{
return new HtmlString($"<p>Welcome, {username}.</p>");
}
}
Run Code Online (Sandbox Code Playgroud)
而@helper当我们想创建HTML和一些逻辑,这意味着我们需要编写代码剃须刀渲染它是有用的。
因为@helper当我们定义的方法需要与 Html 混合并且我们想要返回一些 html 时使用它们。
@helper{
public WelcomeMessage(string username)
{
<p>Welcome, @username.</p>;
}
}
Run Code Online (Sandbox Code Playgroud)
请阅读以下精彩文章,其中详细解释了两者的区别:
| 归档时间: |
|
| 查看次数: |
3132 次 |
| 最近记录: |