Return Templates in CodeBehind: moving loops out of the View
The CodeBehind .NET Core framework introduces Return Templates, a mechanism for keeping loops and conditionals out of the View when generating dynamic HTML. Instead of mixing @foreach into markup or concatenating HTML strings in a Controller, the structure lives in a template variable that gets replaced during processing. The feature works in both Razor and Standard syntax and supports nested, multi-stage resolution.
Key points
- A Return Template is a template variable declared in the markup that is replaced by generated content during processing
- Resolution is recursive, so nested templates are resolved across multiple stages
- Both Razor and Standard syntax are supported, each with its own notation
- The loop moves out of the View into a separate block, so no HTML string concatenation in the Controller
- CodeBehind ships as a NuGet package with its own View model; it is not part of ASP.NET Core
CodeBehind is built on the idea that a View should describe HTML while server-side code handles data and behavior. Return Templates extend that split to loops: a template variable is declared inside the markup, a separate block repeats it for each item, and the generated content replaces the variable. Remaining placeholders are then filled in, so rendering happens in several stages rather than one pass.
In the navigation-menu example, the markup for a single link is written once and the loop only invokes that template, while values such as the title and URL come from their own templates. The same mechanism is available in both Razor and Standard syntax, and the framework handles transitions between server-side code blocks and returned content. The package ships on NuGet; note that this is a separate framework with its own View model, not an ASP.NET Core feature.
Real-world use
- A site that builds its navigation menu from a database-driven list of pages
- Product listing pages where the same card structure repeats dozens of times
- Complex layouts with nested layout and partial templates
- Teams where front-end and back-end developers share the same View
Why it matters
It offers an alternative model for teams that want control flow fully separated from HTML, but it is specific to CodeBehind and does not transfer directly to ASP.NET Core projects.