Problem
In Razor, how can I define a method?
Asked by Rookian
Solution #1
@functions is how you do it, regardless of any discussions about when (if ever) it should be done.
@functions {
// Add code here.
}
Answered by David Ruttka
Solution #2
What do you mean by inline helper?
@helper SayHello(string name)
{
<div>Hello @name</div>
}
@SayHello("John")
Answered by Darin Dimitrov
Solution #3
Defining a function in Razor is fairly simple.
@functions {
public static HtmlString OrderedList(IEnumerable<string> items)
{ }
}
As a result, you can call the method from anywhere. Like
@Functions.OrderedList(new[] { "Blue", "Red", "Green" })
This activity, however, can also be done with the aid of a helper. As an illustration,
@helper OrderedList(IEnumerable<string> items){
<ol>
@foreach(var item in items){
<li>@item</li>
}
</ol>
}
So, what is the distinction? Both @helpers and @functions, according to this earlier piece, have one thing in common: they allow code reuse within Web Pages. They also have one thing in common: they appear to be the same person at first glance, which could lead to some uncertainty about their duties. They are not, however, the same. A helper is a reusable snippet of Razor syntax exposed as a method that is used to render HTML to the browser, whereas a function is a static utility method that can be used from anywhere in your Web Pages application. A helper’s return type is always HelperResult, whereas a function’s return type is whatever you want it to be.
Answered by gdmanandamohon
Solution #4
You may also use a Func like this to do it.
@{
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>
Answered by Bokoskokos
Solution #5
Razor is nothing more than a templating engine.
A standard class should be created.
Put them in a @functions block if you wish to create a method within a Razor page.
Answered by SLaks
Post is based on https://stackoverflow.com/questions/5159877/how-do-i-define-a-method-in-razor