Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET Core Razor C# functions [duplicate]

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

like image 825
TheLovelySausage Avatar asked Feb 03 '17 09:02

TheLovelySausage


People also ask

What is .NET Core Razor?

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.

What is a Razor page C#?

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.

Is Razor better than MVC?

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.


1 Answers

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;
    }
}
like image 98
Marc Gravell Avatar answered Sep 18 '22 06:09

Marc Gravell