razor helps you embed serverside code like C# code into web pages. cshtml is just a file extension. razor view engine is used to convert razor pages(. cshtml) to html.
cshtml file we need to right click on GetEmployeeInfo() Action Method & Click on Add View. From the Add View Window, give the View Name as GetEmployeeInfo, Template as Create, and Model class as EmployeeInfo. cs and click on Add, with this GetEmployeeInfo. cshtml file will be added in Views Folder.
Go to solution explorer => Views Folder => Right-click on “Home” Folder >> go to “Add” >> Click on [New Item] as follow. Select MVC 5 View Page with Layout(Razor) from "Add New Item" window and provide the required name like "ViewPageWithLayout. cshtml" click on "Add" button as follow.
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 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
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 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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With