App
Resources
Reuse Shared Razor Helpers (CreateInstance / GetCode)
There are multiple ways to create shared Razor helpers:
- public functions returning html
⭐ this is recommended in v12 and above as it works in Dnn ✅ and Oqtane ✅ - the
@helper
command
👍 this is simpler, but only works in Dnn ✅ but not in Oqtane ⛔
Razor helpers are functions that put HTML into the page. You can create them using either@functions { dynamic helpername() { ... } }
or@helper helpername() { ... }
You can also share them by placing them into a separate 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 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: