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
@{
var code = CreateInstance("CodeBehindSimulated.cs");
}
<div>Hello from Code Behind: <strong>@code.Hello()</strong></div>
@code.Message("Message in a special format")
Source Code of CodeBehindSimulated.cs
using ToSic.Razor.Blade;
using System.Linq;
using System;
public class CodeBehindSimulated: Custom.Hybrid.Code14
{
public string Hello() {
return "Hello from inner code";
}
// This is an example of a helper returning HTML which will be rendered directly
// You could also do: return Html.Raw(...);
public dynamic Message(string message) {
return Tag.Div(message).Class("alert alert-success");
}
}
@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 })