我如何定义一个方法在剃刀?
当前回答
你是说内联helper?
@helper SayHello(string name)
{
<div>Hello @name</div>
}
@SayHello("John")
其他回答
你也可以使用@{}块来创建函数:
@{
async Task<string> MyAsyncString(string input)
{
return Task.FromResult(input);
}
}
然后在你的剃须刀页后面:
<div>@(await MyAsyncString("weee").ConfigureAwait(false))</div>
在razor中定义一个函数非常简单。
@functions {
public static HtmlString OrderedList(IEnumerable<string> items)
{ }
}
你可以在任何地方调用函数。就像
@Functions.OrderedList(new[] { "Blue", "Red", "Green" })
但是,同样的工作也可以通过helper完成。举个例子
@helper OrderedList(IEnumerable<string> items){
<ol>
@foreach(var item in items){
<li>@item</li>
}
</ol>
}
So what is the difference?? According to this previous post both @helpers and @functions do share one thing in common - they make code reuse a possibility within Web Pages. They also share another thing in common - they look the same at first glance, which is what might cause a bit of confusion about their roles. However, they are not the same. In essence, a helper is a reusable snippet of Razor sytnax exposed as a method, and is intended for rendering HTML to the browser, whereas a function is static utility method that can be called from anywhere within your Web Pages application. The return type for a helper is always HelperResult, whereas the return type for a function is whatever you want it to be.
下面是如何在ASP中编写列表助手。NET Core 3
现在,您可以在代码块中声明的方法体中包含HTML标记,就像以前一样作为本地方法,或者在@functions块中包含HTML标记。方法应该返回 void,或者Task(如果需要异步处理):
@{
void Template(string[] listItems, string style)
{
<ul>
@foreach (var listItem in listItems)
{
<li class="@style">@listItem</li>
}
</ul>
}
}
你是说内联helper?
@helper SayHello(string name)
{
<div>Hello @name</div>
}
@SayHello("John")
Razor只是一个模板引擎。
您应该创建一个常规类。
如果你想在Razor页面中创建一个方法,把它们放在@functions块中。
推荐文章
- 返回文件在ASP。Net Core Web API
- 自定义HttpClient请求头
- 如果我使用OWIN Startup.cs类并将所有配置移动到那里,我是否需要一个Global.asax.cs文件?
- ASP。NET Identity DbContext混淆
- VS2013外部构建错误"error MSB4019: The imported project <path> was not found"
- 从另一个列表id中排序一个列表
- 等待一个无效的异步方法
- 无法加载文件或程序集…参数不正确
- c#中枚举中的方法
- 如何从字符串中删除新的行字符?
- 如何设置一个默认值与Html.TextBoxFor?
- 检查属性是否有属性
- 格式化XML字符串以打印友好的XML字符串
- 返回内容与IHttpActionResult非ok响应
- web页面的功能是什么:在MVC 3 web.config中启用