.NET Core Razor C#函数

The*_*age 4 c# asp.net function razor

我对.NET Core(整体来说是ASP.NET)还是很陌生,我想知道在尝试在View中创建C#函数时是否做任何明显错误的事情

我的看法如下(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>
Run Code Online (Sandbox Code Playgroud)

一切正常,并且可以执行我想要的操作,但是如果我尝试将其组织为功能,甚至添加基本功能,它就会像波纹管一样折断

@{
    // 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>
Run Code Online (Sandbox Code Playgroud)

只是添加该功能会破坏它,我不确定为什么

Mar*_*ell 5

它们在该@functions部分中,您不需要可访问性修饰符:

@functions {
    // function for no reason
    void testFunc()
    {
        string nothing;
        nothing = null;
        return;
    }
}
Run Code Online (Sandbox Code Playgroud)