How do I define a method in Razor?

2020-01-27 12:40发布

How do I define a method in Razor?

7条回答
唯我独甜
2楼-- · 2020-01-27 13:12

You can also just use the @{ } block to create functions:

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

Then later in your razor page:

   <div>@(await MyAsyncString("weee").ConfigureAwait(false))</div>
查看更多
神经病院院长
3楼-- · 2020-01-27 13:15

Leaving alone any debates over when (if ever) it should be done, @functions is how you do it.

@functions {

    // Add code here.

}
查看更多
狗以群分
4楼-- · 2020-01-27 13:21

You mean inline helper?

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

@SayHello("John")
查看更多
我想做一个坏孩纸
5楼-- · 2020-01-27 13:23

It's very simple to define a function inside razor.

@functions {

    public static HtmlString OrderedList(IEnumerable<string> items)
    { }
}

So you can call a the function anywhere. Like

@Functions.OrderedList(new[] { "Blue", "Red", "Green" })

However, this same work can be done through helper too. As an example

@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.

查看更多
叼着烟拽天下
6楼-- · 2020-01-27 13:25

You can simply declare them as local functions in a razor block (i.e. @{}).

@{
    int Add(int x, int y)
    {
        return x + y;
    }
}

<div class="container">
    <p>
        @Add(2, 5)
    </p>
</div>
查看更多
老娘就宠你
7楼-- · 2020-01-27 13:26

Razor is just a templating engine.

You should create a regular class.

If you want to make a method inside of a Razor page, put them in an @functions block.

查看更多
登录 后发表回答