I need to create a function that is only necessary inside one cshtml file. You can think of my situation as ASP.NET page methods, which are min web services implemented in a
In ASP.NET Core Razor Pages, you can combine C# and HTML in the function:
@model PagerModel
@{
}
@functions
{
void PagerNumber(int pageNumber, int currentPage)
{
if (pageNumber == currentPage)
{
<span class="page-number-current">@pageNumber</span>
}
else
{
<a class="page-number-other" href="/table/@pageNumber">@pageNumber</a>
}
}
}
<p>@PagerNumber(1,2) @PagerNumber(2,2) @PagerNumber(3,2)</p>
If your method doesn't have to return html and has to do something else then you can use a lambda instead of helper method in Razor
@{
ViewBag.Title = "Index";
Layout = "~/Views/Shared/_Layout.cshtml";
Func<int,int,int> Sum = (a, b) => a + b;
}
<h2>Index</h2>
@Sum(3,4)
Take a look at Declarative Razor Helpers
why not just declare that function inside the cshtml file?
@functions{
public string GetSomeString(){
return string.Empty;
}
}
<h2>index</h2>
@GetSomeString()
You can use the @helper Razor directive:
@helper WelcomeMessage(string username)
{
<p>Welcome, @username.</p>
}
Then you invoke it like this:
@WelcomeMessage("John Smith")
If you want to access your page's global variables, you can do so:
@{
ViewData["Title"] = "Home Page";
var LoadingButtons = Model.ToDictionary(person => person, person => false);
string GetLoadingState (string person) => LoadingButtons[person] ? "is-loading" : string.Empty;
}