我该如何在Razor中定义一个方法?
我该如何在Razor中定义一个方法?
不管何时(如果有必要)进行操作,@functions 是实现之道。
@functions {
// Add code here.
}
@functions
是组织视图特定生成代码的好地方。 典型例子:那些丑陋的客户端模板字符串... - user2864740您指的是内联辅助函数吗?
@helper SayHello(string name)
{
<div>Hello @name</div>
}
@SayHello("John")
在 Razor 内定义函数非常简单。
@functions {
public static HtmlString OrderedList(IEnumerable<string> items)
{ }
}
所以你可以在任何地方调用函数a。例如:
So you can call a the function anywhere. Like
->所以你可以在任何地方调用函数a。例如:
@Functions.OrderedList(new[] { "Blue", "Red", "Green" })
但是同样的工作也可以通过helper
完成。例如
@helper OrderedList(IEnumerable<string> items){
<ol>
@foreach(var item in items){
<li>@item</li>
}
</ol>
}
那么它们之间有什么区别呢?根据这篇文章,@helper和@function共享了一个共同点——它们使得在Web页面中可以实现代码重用。它们还有另一个共同点——乍一看它们看起来相同,这可能会导致对它们的作用产生一些困惑。然而,它们并不相同。本质上,helper是可重用的Razor语法片段,被暴露为方法,并旨在将HTML渲染到浏览器中,而函数是静态实用程序方法,可以从Web页面应用程序的任何地方调用。helper的返回类型始终为HelperResult,而函数的返回类型可以是您想要的任何类型。
@Functions
前缀直接使用@OrderedList(...)
调用函数对我有效。 - Muflix@{
var getStyle = new Func<int, int, string>((width, margin) => string.Format("width: {0}px; margin: {1}px;", width, margin));
}
<div style="@getStyle(50, 2)"></div>
Func
会分配一个委托并影响性能(稍微一点)。 - Alex from Jitbit@{ }
块来创建函数:@{
async Task<string> MyAsyncString(string input)
{
return Task.FromResult(input);
}
}
<div>@(await MyAsyncString("weee").ConfigureAwait(false))</div>
现在可以在代码块中声明局部方法或@functions块中包含HTML标记。该方法应返回void或Task(如果需要异步处理):
@{
void Template(string[] listItems, string style)
{
<ul>
@foreach (var listItem in listItems)
{
<li class="@style">@listItem</li>
}
</ul>
}
}
MyModelVm.cs
public class MyModelVm
{
public HttpStatusCode StatusCode { get; set; }
}
Index.cshtml
@model MyNamespace.MyModelVm
@functions
{
string GetErrorMessage()
{
var isNotFound = Model.StatusCode == HttpStatusCode.NotFound;
string errorMessage;
if (isNotFound)
{
errorMessage = Resources.NotFoundMessage;
}
else
{
errorMessage = Resources.GeneralErrorMessage
}
return errorMessage;
}
}
<div>
@GetErrorMessage()
</div>
@{
string exampleVariable = "just an example variable";
string anotherExampleVariable = "just another example variable";
string GetErrorMessage()
{
var isNotFound = Model.StatusCode == HttpStatusCode.NotFound;
string errorMessage;
if (isNotFound)
{
errorMessage = Resources.NotFoundMessage;
}
else
{
errorMessage = Resources.GeneralErrorMessage
}
return errorMessage;
}
}