5

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

TheLovelySausage
  • 3,838
  • 15
  • 56
  • 106
  • 3
    "it breaks" doesn't tell us anything about what error you're getting. – Jon Skeet Feb 03 '17 at 09:59
  • All of the old code bellow starts saying the variables aren't declared and when I run the page it shows lines and lines of errors, stuff like '} expected' and 'identifier expected' and 'type expected' at least 50 lines of errors – TheLovelySausage Feb 03 '17 at 10:03
  • Please edit the question to show that, along with a *minimal but complete* example (which includes all the error messages verbatim). I know the question has now been answered and closed, but it's not too late to improve it. – Jon Skeet Feb 03 '17 at 10:18
  • The question is definitely a duplicate though I just didn't realize that Razor had a specific way of defining functions that isn't standard C#. Is it possible to close this question because I don't think it's going to be of use to anyone – TheLovelySausage Feb 03 '17 at 10:22

1 Answers1

11

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;
    }
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900