Table of Contents

C# API

How to use out C# API in templates

Templates are rendered using either ViewModels or TemplateTags to dynamically fetch information from DW10 and render it in frontend when a page is being shown.

Sometimes, however, the ViewModel og tag collection does not contain the properties you want to access in a template - in those cases you can often use our C# API to work directly with DynamicWeb objects and data.

The recommended method is to go via our services:

In the following we will add examples of how you can use the C# api in your templates to extend standard template functionality.

Important

Some considerations before you start:

  • If you only need a piece of code in one template write the code directly in the template
  • If you need the same code in more templates you can:
    • Use ViewModel Extensibility to add properties or change behavior of existing properties
    • Create extension methods for a given ViewModel to add methods that can be re-used and compile these into a package
  • Be careful about code performance in templates - templates are rendered many times, and even small performance issues can become problematic
  • Code in templates should be rendering-logic only - e.g. how the "Add to cart"-button should be rendered, and not 'business'-logic like the price of the product

Example 1: Looking up the user who created a page

In this example we use the PageViewModel to render a blog post. We want to show the reader who wrote the blogpost, a property not on the PageViewModel.

@inherits Dynamicweb.Rendering.ViewModelTemplate<Dynamicweb.Frontend.PageViewModel>

<h1>@Model.Item.GetString("Title")</h1>

<p>Written by @Model.Item.GetString("Author")</p>

<p>
    @Model.Item.GetString("Text")
</p>
<p>
    <img src="@Model.Item.GetFile("Image").Path" />
</p>
<p>
    <a href="@Model.Item.GetLink("Link").Url">Read more</a>
</p>

// Here we use the C# API to look up the name of the user who created this page

@{
    string pageCreatedBy = string.Empty;
    var page = Dynamicweb.Content.Services.Pages.GetPage(Model.ID);
    if (int.TryParse(page.Audit.CreatedBy, out int createdByUserId))
    {
        var user = Dynamicweb.Security.UserManagement.UserManagementServices.Users.GetUserById(createdByUserId);
        pageCreatedBy = $"This page was created by {user.Name}";
    }
}
<p>
    <small>@pageCreatedBy</small>
</p>
To top