Includes & Partial Views

Includes & partial views are ways of rendering a markup file within the output of another markup file’s rendered output. There are several reasons for doing this:

  • To reuse common markup content across several files – place it in a single file and include it when you need it
  • To break up large markup files into smaller components

So what’s the difference between @Include() and @RenderPartial()?

  • @Include() is typically used within TemplateTag-based designs and does not offer intellisense
  • @RenderPartial() is used within ViewModel-based designs – and enables full intellisense inside the partial view

See examples below.

The Include()-method takes a path as the only parameter:

RAZOR
@Include("Footer.cshtml") @Include("Includes/Footer.cshtml")

The @RenderPartial()-method makes it possible to render partial views in a Razor template.  It is an alternative to the existing @Include functionality, but is implemented in a way which enables full intellisense inside the partial view.

RAZOR
@inherits Dynamicweb.Rendering.ViewModelTemplate<Dynamicweb.Frontend.PageViewModel> @Title("Partial view demo") @Description("Demo of how to render partial views") <!DOCTYPE html> <html> <head> <title>@Model.Title</title> </head> <body> @* Use current model *@ @RenderPartial("partials/page.cshtml") @* Use any other model that inherits from ViewModelBase *@ @RenderPartial("partials/page-area.cshtml", this.Model.Area) @RenderPartial("partials/page-properties.cshtml", this.Model.PropertyItem) @RenderPartial("partials/page-cart.cshtml", this.Model.Cart) </body> </html> @functions { /// <summary> /// Renders a partial view using the current view model /// </summary> /// <param name="templatePath">Relative path to a view model template, e.g. "partials/part.cshtml</param> /// <returns>Output from rendering of the view model template</returns> string RenderPartial(string templatePath) { return RenderPartial(templatePath, this.Model); } /// <summary> /// Renders a partial view using the given view model /// </summary> /// <typeparam name="T">The type of viewmodel. The type must inherit from Dynamicweb.Rendering.ViewModelBase</typeparam> /// <param name="templatePath">Relative path to a view model template, e.g. "partials/part.cshtml</param> /// <param name="model">Instance of a view model</param> /// <returns>Output from rendering of the view model template</returns> string RenderPartial<T>(string templatePath, T model) where T : Dynamicweb.Rendering.ViewModelBase { var template = new Dynamicweb.Rendering.Template(templatePath); template.SetViewModel(model); return template.Output(); } }