2

I did some reading and found out that you can now have local functions in razor views: https://learn.microsoft.com/en-us/aspnet/core/mvc/views/razor?view=aspnetcore-3.0#razor-code-blocks

@{
    void RenderName(string name)
    {
        <p>Name: <strong>@name</strong></p>
    }

    RenderName("Mahatma Gandhi");
    RenderName("Martin Luther King, Jr.");
}

And that looks great. But, for some reason this doesn't compile on my machine. Why is that? My target framework is .NetCore 3.1 and Visual Studio 2019 16.6.0. There are some error messages: "Type or namespace definition, or end-of-file expected" - on the very first line (@using statement) and then: "Invalid expression term '<'" on the line with HTML.

What is wrong with that?

Adam Jachocki
  • 1,897
  • 1
  • 12
  • 28

2 Answers2

1

Functions must be declared inside a @functions block in Razor pages.
Here is a related post.

Is this working?

@functions{
    void RenderName(string name)
    {
        <p>Name: <strong>@name</strong></p>
    }
}
@{
    RenderName("Mahatma Gandhi");
    RenderName("Martin Luther King, Jr.");
}
Lucas S.
  • 702
  • 2
  • 11
  • 22
  • This is not working either. Function that I'am asking about, is a "local" function. It doesn't need "functions" block. Please, take a look at the link that I have provided in my post. – Adam Jachocki May 25 '20 at 09:57
0

OK, the solution was really simple. I had a warning that was saying: "Detected Razor downgrade". I just had to remove reference to Microsoft.AspNetCore.Mvc (2.2) which had been added automatically while creating the project in one of previous versions of VisualStudio.

Adam Jachocki
  • 1,897
  • 1
  • 12
  • 28