Skip to main content

Reuse Templates and Code Tutorials

Tutorial Home
#7 Split Razor Templates into C#-Code and Template

Use Code-Behind in Razor Templates (new in V11, deprecated in v12)

Code-Behind is being depraced in v12, because the idea behind it won't work in Oqtane 💧.
We'll continue to support it in Dnn and to use it, you'll have to inherit from Custom.Dnn.Razor12, but we strongly suggest you move to the other features which provide the same functionality:

  1. Reuse CreateInstance instead
    CreateInstance is enhanced in 2sxc 10.01 to support .cs files to share code across Razor files and WebApi Controllers.

Razor Templates should be simple to edit for web designers. When you end up getting complex functions we recommend placing them in a Code-Behind file. This is different from shared code, since the code isn't shared. We're just splitting a razor file into the code-parts and design parts.


Calling a function from the code-behind

This calls the function Hello() from the Code-Behind.

Hello from Code Behind: Hello from inner code

Calling a helper from the code-behind

This creates a special alert-div using a Helper called Message from the Code-Behind.

Message in a special format
#7 Split Razor Templates into C#-Code and Template

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

@* Note that the Code-Behind features requires this @inherits statement *@
@inherits Custom.Hybrid.Razor14
<!-- unimportant stuff, hidden -->

Use Code-Behind in Razor Templates (new... <!-- unimportant stuff, hidden -->

<hr>
<h2>Calling a function from the code-behind</h2>
This calls the function Hello() from the... <!-- unimportant stuff, hidden -->

<div>Hello from Code Behind: <strong>@code.Hello()</strong></div>

<hr>
<h2>Calling a helper from the code-behind</h2>
This creates a special alert-div using a... <!-- unimportant stuff, hidden -->

@code.Message("Message in a special format")

<!-- unimportant stuff, hidden -->

Source Code of _410CodeBehind.cs

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

using ToSic.Razor.Blade;
using System.Linq;
using System;

public class _410CodeBehind: 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");
  }
}