Code-Behind Strategy in Razor Templates
Code-Behind is a concept where you place the code file separately from the razor file itself. This helps you place large chunks of logic in another file. 2sxc had a built-in feature in v11 but it couldn't be transferred to Oqtane đŸ’§, so it was deprecated in v12.
But you can still use this strategy if you need it. Just create a SomeCode.cs
file and use that.
Calling a function from the simulated Code-Behind
This two examples do the following:
- Call the function
Hello()
- This creates a special alert-div using a Helper called
Message(...)
Output
Hello from Code Behind: Hello from inner code
Message in a special format
Source Code of this file
Below you'll see the source code of the file. Note that we're just showing the main part, and hiding some parts of the file which are not relevant for understanding the essentials. Click to expand the code
@inherits Custom.Hybrid.Razor14 @using ToSic.Razor.Blade; <!-- unimportant stuff, hidden --> Code-Behind Strategy in Razor Templates... <!-- unimportant stuff, hidden --> @{ var code = CreateInstance("CodeBehindSimulated.cs"); } <div>Hello from Code Behind: <strong>@code.Hello()</strong></div> @code.Message("Message in a special format") @* Footer *@ @Html.Partial("../Shared/Layout/FooterWithSource.cshtml", new { Sys = Sys })