I'm pretty new to .NET Core (ASP.NET on the whole) and I was wondering if I'm doing anything obviously wrong when trying to create a C# function inside my View
my view is as follows (Collections.cshtml)
<h2>Collections</h2>
<div id="content">
@{
// define variables
List<string> collections;
int counter;
// build list
collections = new List<string>();
collections.Add("Nothing 01");
collections.Add("Nothing 02");
// display list
counter = 0;
while(counter < collections.Count)
{
<p>@collections[counter]</p>
counter = counter + 1;
}
}
</div>
That all works fine and does what I want it to do but if I try to organize it into functions or even add a basic function it breaks like bellow
@{
// function for no reason
public void testFunc()
{
string nothing;
nothing = null;
return;
}
}
<h2>Collections</h2>
<div id="content">
@{
// define variables
List<string> collections;
int counter;
// build list
collections = new List<string>();
collections.Add("Nothing 01");
collections.Add("Nothing 02");
// display list
counter = 0;
while(counter < collections.Count)
{
<p>@collections[counter]</p>
counter = counter + 1;
}
}
</div>
Just adding that function breaks it and I'm not sure why
Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views. If you're looking for a tutorial that uses the Model-View-Controller approach, see Get started with ASP.NET Core MVC. This document provides an introduction to Razor Pages. It's not a step by step tutorial.
Razor Pages is a newer, simplified web application programming model. It removes much of the ceremony of ASP.NET MVC by adopting a file-based routing approach. Each Razor Pages file found under the Pages directory equates to an endpoint.
From the docs, "Razor Pages can make coding page-focused scenarios easier and more productive than using controllers and views." If your ASP.NET MVC app makes heavy use of views, you may want to consider migrating from actions and views to Razor Pages.
They go in the @functions
section, and you don't need an accessibility modifier:
@functions {
// function for no reason
void testFunc()
{
string nothing;
nothing = null;
return;
}
}
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