我如何定义一个方法在剃刀?


当前回答

Razor只是一个模板引擎。

您应该创建一个常规类。

如果你想在Razor页面中创建一个方法,把它们放在@functions块中。

其他回答

先不讨论什么时候(如果有的话)应该做这件事,@functions就是你做这件事的方式。

@functions {

    // Add code here.

}

你也可以使用@{}块来创建函数:

@{
    async Task<string> MyAsyncString(string input)
    {
        return Task.FromResult(input);
    }
}

然后在你的剃须刀页后面:

   <div>@(await MyAsyncString("weee").ConfigureAwait(false))</div>

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>

您也可以使用下面的代码块。它更干净,功能更丰富。你也可以在上面插入变量,在下面插入函数。而不是使用2个单独的代码块。

@{
    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;
    }
}

你是说内联helper?

@helper SayHello(string name)
{
    <div>Hello @name</div>
}

@SayHello("John")

Razor只是一个模板引擎。

您应该创建一个常规类。

如果你想在Razor页面中创建一个方法,把它们放在@functions块中。