When your Razor gets a bit more complex, you'll either want to split your files a bit to organize them better, or move partial views/templates into separate files. This is very easy using @RenderPage.
I'm writing about this, because many people somehow don't seem to know about this - so it's simple, but important.
The Basics of RenderPage
This is more or less all you have to write
- RenderPage("_2SexyContent Feature - List.cshtml")
or often inside a div/span etc:
- <div>@RenderPage("_2SexyContent Feature - List.cshtml") </div>
And I'm sure you guessed it: the stuff in the quotes is a file, relative to the location of your initial file. Simple, right?
Simple Stuff: The Result
Remember that razor and ASP.net Views (MVC, Core, etc.) are basically just a few simple objects passed around. So the result of RenderPage is a HelperResults string. This means that if you just render the result to as part of the page, the HTML will be used as is (just what you want). But if you would use the result in any kind of string-manipulation, you'll have to @Html.Raw(...) it first, to ensure the HTML can be used.
A Dit Hard: Parameters
If you want to use sub-views a bit like an external template expecting some parameters, you can just add that to the call, like
Data can be anything you want it to be, like a single value or a dictionary of values which the internal template expects. The internal template will be able to use this data by accessing the variable PageData. So you could create a simple CSHTML which simply expects a list of items and generates a table for that.
The Hard Stuff: Data for the Sub-View
This is so simple, that people tend to forget what's happening behind the hood, and are then surprised when things work a bit differently. So I want to help you understand what really happens. Basically if you want the sub-view to have much more than just the parameters, then the Razor-Host which runs the main page must do that for you. Here's some stuff you may want in your inner template
- DNN objects
- Helper commands like AsDynamic
- The full set of data which the original view had
- Webserver stuff like the Request object
This sound logical and obvious, and it's basically all taken care for you...if you use the right razor host. Because the Razor-Host itself MUST take care of this. Otherwise it ain't gonna happen. So if you're using this method and feel like you're missing something.
The default razor host of asp.net will do a bit of this, the razor-host in DNN will do a bit more. The 2sxc-razor host will ensure that all inner templates have access to the full, initialized set of information which the main template had. Because of this you can easily create a list-template and a view-template, and call them from the main file as you need, like in the following example: