Skip to main content
Home  › ... 2sxc Apps

Reuse Templates and Code Tutorials

Tutorial Home

Reuse Shared Templates

Partial templates are cshtml files which you can use multiple times. Typically they will contain something which you need in many places, like a menu or a data-visualizer which gets data as a parameter, and then creates a different table each time. Here's how to use it with Html.Partial(...) (or RenderPage in older versions).


Just render the same, external file into here

This uses @Html.Partial to get the file _line.cshtml 3 times.





@Html.Partial("_line.cshtml")
@Html.Partial("_line.cshtml")
@Html.Partial("_line.cshtml")

Passing in values

The next example passes in a word to the sub-template, so that can change what it does based on the variable. The called template will get the parameters on DynamicModel (see code below)

Hello, this is the first line
Second line!
I'm last!

@Html.Partial("_box.cshtml", new { Label = "Hello, this is the first line" })
@Html.Partial("_box.cshtml", new { Label = "Second line!", Color = "red" })
@Html.Partial("_box.cshtml", new { Label = "I'm last!", Color = "blue" })

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

@inherits Custom.Hybrid.Razor14
<!-- unimportant stuff, hidden -->

Reuse Shared Templates Partial templates... <!-- unimportant stuff, hidden -->

<hr>
<h3>Just render the same, external file into here</h3>
<!-- unimportant stuff, hidden -->

@Html.Partial("_line.cshtml")
@Html.Partial("_line.cshtml")
@Html.Partial("_line.cshtml")




<hr>
<h2>Passing in values</h2>
<!-- unimportant stuff, hidden -->

@Html.Partial("_box.cshtml", new { Label = "Hello, this is the first line" })
@Html.Partial("_box.cshtml", new { Label = "Second line!", Color = "red" })
@Html.Partial("_box.cshtml", new { Label = "I'm last!", Color = "blue" })



<!-- unimportant stuff, hidden -->

Source Code of _line.cshtml

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

@inherits Custom.Hybrid.Razor14
<hr style="height: 10px; border: 1; box-shadow: inset 0 9px 9px -3px rgba(11, 99, 184, 0.8); border-radius: 5px;">

Source Code of _box.cshtml

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

@inherits Custom.Hybrid.Razor14
@{
  // pick up parameters which were passed in
  var label = DynamicModel.Label;
  var color = DynamicModel.Color as string ?? "black"; // default to "black" if not provided
}
<div style="border: solid 2px @color">
  @label
</div>