Resources
Use Shared C# Code
The best way shared C# helpers:
- public functions returning strings, objects, ints etc.
- public functions returning html using RazorBlade
This is recommended in v12 and above as it works in Dnn ✅ and Oqtane ✅
You share them by placing them into a separate CS file (just remember to mark them public
). This lets you put a bunch of tiny helpers into a helpers-library and use them from elsewhere.
To achieve this, we use CreateInstance
to get an object with these methods, and then use it.
Switch to Strong-Typed (2sxc 17.06+) Switch to Typed (2sxc 16+) Selected: Dynamic (Razor14 or below)
Reuse Code with .cs Files
Starting with 2sxc 10.01 CreateInstance()
can also be used with .cs files, from both razor pages as well as WebApi controllers. This allows you to create shared code which can be used in Razor and WebApi controllers.
Note that in 2sxc 16.05 we recommend you use GetCode()
instead.
The example takes a cs file with shared code, but gets the class Second
.
⬇️ Result | Source ➡️
Often you may need context - like the Dnn
or App
objects. We made this easy by defining a base class you can inherit from, called Custom.Hybrid.Code14
(previously ToSic.Sxc.Dnn.DynamicCode
). If you use that as your base-class, all existing context is automatically attached, allowing you to access variables like App
.
⬇️ Result | Source ➡️
The mechanism above also works in WebApi Controllers (if you have 2sxc 10.01+). Note that specifically in WebApi you can only use GetCode(...)
for .cs
files.
⬇️ Result | Source ➡️
Click to see the result of a WebApi call with the shared code: