Skip to main content

Razor Tutorial - Home (14.7.5)

Below you'll find a list of topics this tutorial covers. The easiest way to work with it is to look at an example, then look at the code shown below the examples.

Razor Basics

Learn how to use variables and loops, encode HTML, use 🚀😁💪 Emojis.
Also advanced stuff like re-using code or setting page titles and SEO stuff.
  1. Variables

    Create variables and show using @variableName

  2. Conditions

    if/else and ternary operator (condition ? true : false)

  3. Loops

    Loops using for() and foreach()

  4. Work with HTML

    Learn the difference of showing variables with @variable and @Html.Raw(variable), and re-use very simple snippets

  5. Using Emojis / Emoticons 👍

    Show Emojis in your output or use them for showing true/false

  6. Advanced Hybrid Use new in v12

    Use compiler Preprocessor Directives to enable Hybrid Razor


Basics: Link between Pages and Views

Learn how to use Link.To(...) to link to specific pages or to link to the same page with certain URL parameters. 

  1. URL Parameters (text)

    Working with text URL Parameters like ?sort=ascending

  2. URL Parameters (number)

    Working with number URL Parameters like ?id=27

  3. Preserve Parameters

    Learn how to create links using current URL parameters

  4. View Switch

    Learn how to switch between views using Link.To()

  5. Working with difficult URLs (new!)

    Working difficult URLs like images containing umlauts


Basics: Re-Use Code and Templates Across Files

You can place common templates, hlp and functions into shared files - both .cshtml and .cs. And you can split Razor files into code and templates.You can place common templates, hlp and functions into shared files - both .cshtml and .cs. And you can split Razor files into code and templates.

  1. Introduction Reuse templates and code

    Explains the basics of re-using code across templates and code files. 

  2. Template-Delegate Helpers - Razor-Style Functions

    Shows how to create simple functions which use the classic Razor-style syntax.

  3. Razor Components with @Html.Partial and DynamicModel

    Reuse Razor files by calling them using @Html.Partial and passing parameters in DynamicModel.

  4. Reuse Razor Helpers (mini-templates) with CreateInstance

    Use a shared razor file to hold multiple functions / helpers, and call them one-by-one as needed. 

  5. Reuse a function library CreateInstance

    Reuse a .cs file with shared functions using CreateInstance

  6. Advanced code reuse with .cs files

    Advanced uses of CreateInstance to share code across Razor files and WebApi Controllers.

  7. Split Razor Templates into C#-Code and Template deprecated, Dnn Only

    Now you can split out complicated C# code so designers don't have to worry about it.


Basics: Set Page Title, Keywords etc. and Headers

Use the IPageService to set page properties, base tags and headers - even JsonLD and OpenGraph.
  1. Page Title, Keyword, Description

    Get/Set Page Title, Keywords, Description and set meta-tags and more.

  2. Base tag in header

    Add a base tag to the header - which works correctly in DNN. Important for SPA JS applications.

  3. Page Icons for Favicon, Apple/Android

    Add various combinations of icons to the page header

  4. Meta and other Tags in header

    Add a base tag to the header - which works correctly in DNN. Important for SPA JS applications.

  5. JSON-LD Headers for SEO

    Add JSON-LD (Linked Data) headers for Google

  6. Open-Graph headers for Social Media

    Add Open-Graph data headers for Facebook, Twitter and other sharing-systems


Basics: Get Information about Site, Page, User, etc.

To enable Hybrid Razor which works on Dnn and Oqtane, we need standards so that our Dynamic Code can access information about the page, module etc. 


Show Content and Data Entities on a Page

In most cases a template will run in a context - so something prepared data for the template, which should now be visualized. These examples assume you're working with 2sxc, which lets editors work with content - and your template only needs to visualize it.
  1. Working with Entity (Item) Values

    Every thing is an Entity. Here some basic examples how to show values like Name, Birthday etc. of such an Entity.

  2. Show current Content in the Ouput

    Show content which was entered for this module


Data

Access App-Data directly or from an App-Query. Learn to query the data in C# using LINQ and work with SQL and JSON

  1. Introduction to Data

    Overview about all the basics like Data vs. App.Data, App.Data.Query etc.




Data: Json

Easily work with JSON data.

Images, Automatic Resizing and Responsive Pictures

Learn the basics of Images, Image Resizing and Pictures.

  1. Introduction to the <img> Tag and Image formats

    Basics of showing images in HTML and understand JPG vs. PNG vs. WebP.

  2. Resize and Crop Images on the Server

    Learn to use the built-in Image-Resizer to create perfect images no matter what the editor adds in the CMS.

  3. Resize using Resize-Settings

    Store all the resize-parameters in a variable for re-use.

  4. Resize and Crop using Global Presets

    Site-wide and App-Wide Presets help to resize with the same settings everywhere.

  5. Resize combining Presets with Custom Resize-Settings

    Merge presets with custom settings.

  6. Responsive Server-Side Images (img) for real pros!

    Professional sites give each screen the best possible picture using srcset and <img>

  7. Responsive and optimal Server-Side Images (picture) for real pros!

    Give each screen the best possible picture based on resolution and format using srcset and <picture>

  8. Leverage the picture tag to the fullest

    Learn the newest best practices using the image service


Multi-Language Content and Resources (i18n) 🌐

2sxc is super-powerful with multiple languages. It's actually one of the best multi-language solutions in all known CMS solutions out there.
  1. Using multiple languages
    Everything in 2sxc can be multi-language. Discover how!

Advanced Settings and Automation

  1. Read Global/Site/App/View Settings using the Settings object 🆕 new in v12
  2. Deep dive into the Settings stack 🆕 new in v12
  3. Use PageService.Activate to enable features, Css and Js 🆕 new in v12

    Imagine controlling web resources/features in central management. No duplicate loading, full control!


RazorBlade Tutorials

These examples help you quickly do hard stuff, once you've mastered the basics above

  1. RazorBlade Introduction - Making real tasks easier

    Properly create preview-texts, strip HTML, pick the right variables, set page titles and way more. 


RazorBlade Examples for Text Manipulations

Helpers to get the non-empty string, get parts of a specific string, trim-to-ellipsis and more.

  1. RazorBlade - Text.Crop() and Text.Ellipsis()

    Correctly crop text without splitting words or html-characters like &

  2. RazorBlade - Text.Has() tells you if something really has content

    Check if strings really have something correctly, incl. spaces or even   whitespaces.

  3. RazorBlade - Text.First() lets you pick a value from many variables RB 3.00

    Often you have to check many variables to find the first one to use.

  4. RazorBlade - Text.Zip() lets you shrink all spaces, tabs, enters together

    Very often you need to clean up some text before working with it.

  5. Razorblade - Text.After(), Text.AfterLast(), Text.Before(), Text.BeforeLast(), Text.Between() RB 3.09 / 2sxc 13.02

    Choose where to split text and retrieve the optimal form


RazorBlade for Manipulating Html Strings

Clean out tags, remove specific attributes, replace <br> with new-lines etc.

  1. Convert <br> tags to new-lines or just spaces - and also the other way around RB 1.00

    A common challenge is showing text as HTML or the other way around

  2. Use Scrub to Remove All or Specific HTML Tags RB 3.09 / 2sxc 13.02

    Remove html from a string - important for teaser texts and protecting against cross-site-scripting attacks.

  3. Use Scrub to remove Tag-Attributes, Classes, Styles or whatever you need RB 3.09 / 2sxc 13.02

    Clean out all kinds of HTML attributes


RazorBlade Examples for Modifying DNN Page Headers

2sxc 12 introduces the new PageService which also works in Oqtane 💧. We suggest you use that instead. 👉 See Razor Page Service

  1. Page Title, Keyword, Description v1.01

    Get/Set Page Title, Keywords, Description and set meta-tags and more.

  2. Base tag in header v3.00

    Add a base tag to the header - which works correctly in DNN. Important for SPA JS applications.

  3. JSON-LD Headers for SEO v1.01

    Add JSON-LD (Linked Data) headers for Google

  4. Open-Graph headers for Social Media  v1.01

    Add Open-Graph data headers for Facebook, Twitter and other sharing-systems

  5. Page Icons for Favicon, Apple/Android v2.01

    Add various combinations of icons to the page header

     

RazorBlade Basic API to Generate Safe Attributes

  1. Safe Html5 Attributes from code  new! v3.00

    Working with attributes in your code to stay error-free

  2. Json Html5 Attributes from code  new! v3.00

    Working with attributes in your code to stay error-free


RazorBlade Fluent Html5 API

RazorBlade 3 contains over 130 objects with hundreds of properties so you can quickly generate Html5 tags correctly and safely.
  1. RazorBlade - using the Html5 Tag API
    The basics of creating html directly from code - new in 2.0 and enhanced in 2.1
  2. Introduction to the Fluid Html5 API with 130+ objects like Img, Table etc.  new! v3.00

    The basics of creating html directly from code

  3. Common Attributes (Id, Title, Class, Style) with SmartJoin new! v3.00

    Some attributes can be added, others replace the previous content. The attributes are super smart 💡

  4. Images with Unsafe URLs (Umlauts etc.) new! v3.00

    The API automatically fixes unsafe URLs like Umlauts, japanese characters etc. - SuperSmart 😎

  5. Picture Tags for various sizes / resolutions  new! v3.00

    Here's an example how to easily generate picture tags, which are the future of Images

  6. Start and End Tags new! v3.00

    In some cases you may want to just get the start or end-tag.

  7. Create custom (non Html5) tags new! v3.00

    Working with tags in your code to stay error-free and do amazing stuff


Koi Tutorials

These examples help you do cool stuff, once you've mastered the basics above
  1. Introduction - Koi - Cool things with CSS-Frameworks and Classes enhanced for v12
    Automatically include missing frameworks, conditionally modify the HTML or CSS-Classes and more, depending on what CSS-framework is used by the theme of this page.
  2. Koi - Auto-Add Bootstrap4 if missing

    Automatically add the Bootstrap4 CSS package from a CDN, if the current theme does not include Bootstrap4 already, but skip it if it's already included.

  3. Koi - Auto-Add Bootstrap4 but inform Admin

    Automatically add the Bootstrap4 CSS package from a CDN (same as above), but also show a warning to admins that this happened.

  4. Koi - Switch between template files new!

    Automatically switch between Bootstrap3 and Bootstrap4 templates.


JavaScript

2sxc offers powerful helpers to just get things done - or to do things your way.
  1. Get Data from the Backend using JS
    Use the 2sxc data API and get data of a specific Content-Type
  2. Get a Query from the Backend using JS
    Use the 2sxc data API and get data from a Query
  3. Add Parameters to Query from the Backend using JS
    Use the 2sxc data API and get data from a Query using Parameters
  4. Create data, update and delete using JS APIs
    Use the 2sxc data API and create, update, delete data
  5. Create Metadata using JS APIs
    Use the 2sxc data API and create new metadata

turnOn

Use the turnOn feature to execute Javascript functions from Razor files
  1. Execute JavaScript with turnOn new in v12
    Use the turnOn feature to execute Javascript functions from Razor files
  2. Basic turnOn usage and activation

    Activate turn-on and execute local JavaScript functions

  3. Passing parameters with turnOn

    Pass parameters to JavaScript functions with turnOn

  4. Passing module parameters with turnOn

    Pass module parameters to JavaScript functions with turnOn

  5. Passing anonymous objects as parameters with turnOn

    Pass anonymous object to JavaScript functions with turnOn

  6. Wait for multiple scripts

    Await a library before executing JavaScript functions

  7. Await custom conditions through functions

    Await custom conditions before executing JavaScript functions

  8. Await system scripts

    Await a system script before executing JavaScript functions


WebApi / JSON Endpoints Examples

These examples show how to create and use WebApi. This isn't Razor, but also uses C#. You'll often need this when creating JavaScript and SPA apps.
  1. Introduction to WebApi
    Provide data to SPAs and do things like sending mails, changing data and more.
  2. WebApi - Very basic examples

    Creating the simplest possible hello WebApi and a Square(number) Api.

  3. WebApi - Basic example with CSRF protection

    This is almost the same as the simplest WebApi, but with additional Cross-Site-Request protection.

  4. WebApi - Basic example using all HTTP methods

    This is almost the same as the simplest WebApi, but with more methods.

  5. WebApi - Bare Metal for custom requests

    Advanced use cases where you need the url/headers but will do the request yourself.

  6. WebApi Polymorph - basic examples

    Basic example showing the same API in a live and staging editior, so you can develop while the users still use the sable one.

  7. WebApi App.Data - basic examples

    Basic example reading App Data.

  8. WebApi App.Query - basic examples

    Basic example reading App Query.

  9. Basic Hybrid WebApi

    Basic example reading App Data.


Customize Edit UI / UX

Sometimes you want to customize what the editor will experience - using special toolbars or custom input fields. Note that this only applies to 2sxc.

Formulas (new!)

Add custom UI logic to your edit forms with formulas.

  1. Getting Started with Formulas

    Create Your First Formula

  2. Value Formulas

    Formulas affecting the Value of a Field

  3. Formulas for DropDowns

    Change what options are available in a DropDown

  4. Formulas for Field-Settings

    Formulas affecting Settings such as Required, Collapsed, Disabled, etc.

  5. Formulas for Field-Groups

    Modify Groups - auto-collapse based on rules, change help texts etc. 

  6. Formulas using parameters new!

    Create formulas using page parameters

  7. Formulas using REST or WebApi Calls new!

    Collection of previous samples, just all these using REST or WebApi.


Crazy 2sxc Advanced Examples

These are really advanced examples and meant more to give guidance for specific questions. Don't worry if you don't understand these

Next Tutorials (Work-In-Progress)

We'll create some more tutorials in 2022, incl. the following
  1. UI Formulas
  2. Linking around in dnn
  3. Using js/css and image resources in the app folder
  4. Using app settings and resources
  5. Navigation links
  6. Leveraging Connect.Koi
  7. Permission examples
  8. In-Page Editing experience
  9. Customizing Search Results
  10. Work with icon-fonts, font-awesome etc.
  11. More data examples, working with users, SQL-write, PetaPoco etc.
  12. Working with DataSources in all kinds of ways
  13. Using data from other apps
  14. Customizing search from data
  15. Custom dynamic WebApi