Skip to main content
Home  › ... Razor

Quick Reference / Cheat-Sheet

Tutorial HomeQuick-Ref
#1 Quick Reference for all APIs

Quick Reference for all APIs

This is a quick CheatSheet to provide you with a reference to most APIs you'll use.

This uses a base class of @inherits Custom.Hybrid.Razor14 and would also apply to ...Razor12. Most samples do not work for the new @inherits Custom.Hybrid.Razorpro as that provides different objects and methods. that uses a different syntax.

The samples can differ based on your Razor base class or if you're running an old version.
Switch to Typed (2sxc 16+) Switch to Dynamic (Razor14 or below)

Razor Basics @...

Common basics for working with Razor.

  1. Show firstName (string): Terry
  2. Show birthday (DateTime):
    4/28/1948 12:00:00 AM
  3. Show birthday (DateTime, formatted):
    1948-04-28
  4. Show age (int): 76
  5. Show decades (int): 7
  6. Show decadesFloat (float): 7.6
  7. Show decadesInt (int): 7
@inherits Custom.Hybrid.Razor14

@{
  // Create variables using var; compiler detects the type
  var firstName = "Terry";
  var birthday = new DateTime(1948, 04, 28);
  var age = DateTime.Now.Year - birthday.Year;
  var decades = age / 10;             // int division - decades will be int
  var decadesFloat = (float)age / 10; // float div - so it be float
  int decadesInt = (int)decadesFloat; // this drops the decimal places
}
<ol>
  <li>Show firstName (string): @firstName</li>
  <li>
    Show birthday (DateTime): <br>
    @birthday
  </li>
  <li>
    Show birthday (DateTime, formatted): <br>
    @birthday.ToString("yyyy-MM-dd")
  </li>
  <li>Show age (int): @age</li>
  <li>Show decades (int): @decades</li>
  <li>Show decadesFloat (float): @decadesFloat</li>
  <li>Show decadesInt (int): @decadesInt</li>
</ol>
  1. Basic set variable and show

    Create variables and show using @variableName

⬇️ Result | Source ➡️

Show old/not old based on Terry's age using @if and @else: this guy is old

Ternare show old/not old based on age ? ... : : this guy is old

@inherits Custom.Hybrid.Razor14

@{
  const int old = 60;
  const string isOld = "this guy is old";
  const string notOld = "this guy is not old";
  var age = 62;
}
<p>
  Show old/not old based on Terry's age using
  <code>@@if</code> and <code>@@else</code>:
  @if (age > old) {
    @isOld
  } else {
    @notOld
  }
</p>
<p>
  Ternare show old/not old based on age <code>? ... : </code>:
  @(age > old ? isOld : notOld)
</p>
  1. Razor Conditions such as if, if-else and ? :

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

Demostrates C# 6 and 7 in Razor. C# 7.3 must be installed this to work - see docs.

⬇️ Result | Source ➡️

C# 6 Features

Demonstrates C# 6 features in Razor views.

Call various properties / functions C# 6

  1. Expression bodied Function: 62
  2. Expression bodied Property: 62
  3. Auto property initializer: 62
  4. Read-Only property initializer: 62

Show old/not old based on Terry's age using @if and @else: this guy is old

Ternare show old/not old based on age ? ... : : this guy is old

@inherits Custom.Hybrid.Razor14
<h2>C# 6 Features</h2>
<p>
  Demonstrates C# 6 features in Razor views.
</p>
<h3>Call various properties / functions C# 6</h3>
<ol>
  <li>Expression bodied Function: @GetAge()</li>
  <li>Expression bodied Property: @Age</li>
  <li>Auto property initializer: @AgeProperty</li>
  <li>Read-Only property initializer: @AgeReadOnlyProp</li>
</ol>
@functions {
  // expression bodied function - C# 6.0
  public string GetAge() => "62";

  // expression bodied properties - C# 6.0
  public int Age => 62;

  // Auto property initializers - C# 6.0
  public int AgeProperty { get; set; } = 62;
  public int AgeReadOnlyProp { get; } = 62;

  // Index initializers - C# 6.0
  public Dictionary<string, string> Dict => new Dictionary<string, string>() {
    ["key1"] = "value1",
    ["key2"] = "value2",
    ["key2"] = "value3"  // this will overwrite the previous value
  };
}

@{
  const int old = 60;
  const string isOld = "this guy is old";
  const string notOld = "this guy is not old";
  var age = 62;

  string testNull = null;
  var length = testNull?.Length;

  var array = new[] { 1, 2, 3 };
  var first = array?[0];

  var message = $"this is a {nameof(age)}";
}
<p>
  Show old/not old based on Terry's age using
  <code>@@if</code> and <code>@@else</code>:
  @if (age > old) {
    @isOld
  } else {
    @notOld
  }
</p>
<p>
  Ternare show old/not old based on age <code>? ... : </code>:
  @(age > old ? isOld : notOld)
</p>

⬇️ Result | Source ➡️

Loop through Pets using
@foreach (var thing in list)

  • dog
  • cat
  • mouse

Loop through Pets using
@for (counter; condition; increment)

  • dog - owned by Daniel
  • cat - owned by John
  • mouse - owned by Markus
@inherits Custom.Hybrid.Razor14

@{
  var pets = new string[] { "dog", "cat", "mouse"};
  var owners = new string[] { "Daniel", "John", "Markus"};
}
<h4>
  Loop through Pets using <br>
  <code>@@foreach (var thing in list)</code>
</h4>
<ul>
  @foreach (var pet in pets) {
    <li>@pet</li>
  }
</ul>
<h4>
  Loop through Pets using <br>
  <code>@@for (counter; condition; increment)</code>
</h4>
<ul>
  @for(var i = 0; i < pets.Length; i++) {
    <li>@pets[i] - owned by @owners[i]</li>
  }
</ul>
  1. Loops - for and foreach

    Loops using for() and foreach()

⬇️ Result | Source ➡️

Output values (HTML-source shown)

  • this is text, it doesn't have tags
  • this string <em>has</em> html <strong>tags</strong>

Output values (HTML is used; maybe security risk)

  • this is text, it doesn't have tags
  • this string has html tags
@inherits Custom.Hybrid.Razor14

@{
  var normalText = "this is text, it doesn't have tags";
  var htmlText = "this string <em>has</em> html <strong>tags</strong>";
}
<h4>Output values (HTML-source shown)</h4>
<ul>
  <li>@normalText</li>
  <li>@htmlText</li>
</ul>
<h4>Output values (HTML is used; maybe security risk)</h4>
<ul>
  <li>@Html.Raw(normalText)</li>
  <li>@Html.Raw(htmlText)</li>
</ul>
  1. Work with HTML Output

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

⬇️ Result | Source ➡️

You can just use any Emoji in your source. Or you pick them with ternary operations.

  • This is just an emoji: 🚀
  • Pick emoji from true ⇒ ✔️
  • Pick emoji from true ⇒ ❌
@inherits Custom.Hybrid.Razor14

<p>
  You can just use any Emoji in your source.
  Or you pick them with ternary operations.
</p>
<ul>
  <li>This is just an emoji: 🚀</li>
  <li>Pick emoji from true ⇒ @(true ? "✔️" : "❌")</li>
  <li>Pick emoji from true ⇒ @(false ? "✔️" : "❌")</li>
</ul>
  1. Working with 😃 Emojis / Emoticons

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

Reuse Razor and CSharp Files

Don't-Repeat-Yourself (DRY) by reusing code in Razor and helper C# files.

⬇️ Result | Source ➡️

Reuse some functions inside this file

  • Boolmoji(true) ⇒ 👍🏽
  • Boolmoji(false) ⇒ 👎🏽
  • Random number function: 86
  • Random number function: 57
  • this is a bold item in a list using a Template Delegate
  • another bold item in a list using a Template Delegate
@inherits Custom.Hybrid.Razor14

@functions {
  string Boolmoji(bool value) { return value ? "👍🏽" : "👎🏽"; }
  
  // Variable keeping the random number generator
  private Random generator = new Random(DateTime.Now.Second);

  // Get random number between 0 and 100
  public int Random100() {
    return generator.Next(0, 100);
  }
}
@{
  // Simple Hybrid (Dnn/Oqtane) Template Delegate
  Func<string, dynamic> BoldLi = @<li>
    <strong>
      @Html.Raw(item)
    </strong>
  </li>;
}
<h4>Reuse some functions inside this file</h4>
<ul>
  <li>Boolmoji(true) ⇒ @Boolmoji(true)</li>
  <li>Boolmoji(false) ⇒ @Boolmoji(false)</li>
  <li>Random number function: @Random100()</li>
  <li>Random number function: @Random100()</li>
  @BoldLi("this is a bold item in a list using a Template Delegate")
  @BoldLi("another bold item in a list using a Template Delegate")
</ul>
  1. Code - Function and Similar Helpers

    Normal C# functions are the basic block for reusing code. 

  2. Use Shared C# Code

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

  3. Reuse Code and Razor Templates

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

Work with Content Items - MyItem

MyItem is the object which contains the first thing added by the editor on the current block.

Work with List of Items - MyItems

Data and Query - MyDataApp.GetQuery(...) and AsItems(...)

Work with Settings and Resources

Settings can be configured at many levels, the most-local (eg. the App) would override the most global (eg. Presets).

Page, Site, Platform and More

Set Page Title, Keywords etc.

⬇️ Result | Source ➡️

Note: you won't see any output here. To see the effect, look at the page source.

@inherits Custom.Hybrid.RazorTyped

<p>
  Note: you won't see any output here.
  To see the effect, look at the page source.
</p>
@* Example with a single-liner directly in the code *@
@Kit.Page.SetTitle("Reference CheatSheet for Razor in 2sxc")
@Kit.Page.AddIconSet(App.Folder.Url + "/assets/icons/razor-blade-icon.png")
@Kit.Page.AddMeta("tutorial", "some value")

@{
  // Example showing how to use in a block of code
  Kit.Page.SetDescription("Learn to use Razor Blade ");
  Kit.Page.SetKeywords("Tutorial, Razor, Blade");
}

Output is Invisible as it only affects the HTML Head

This sample modifies the HTML head, so it's not visible here. 

To see the effect, look at the source in the browser

  1. Set Page Title, Keywords, Descriptions etc.

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

  2. Set <base> tag in header

    Add a <base> tag to the header. This is 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 all kinds of meta-tags to the header. 

Set OpenGraph Headers etc.

⬇️ Result | Source ➡️

This uses Kit.Page.SetTitle(...) and other methods to modify the HTML sent to the browser. It sets various aspecs such as title or FavIcons.

  1. meta title, meta description, meta keywords
  2. favicon
  3. some JsonLd for google
  4. OpenGraph headers for FaceBook, Twitter, etc.
@inherits Custom.Hybrid.Razor14

@* Create a JSON-LD using an object - replicating googles example https://developers.google.com/search/docs/guides/intro-structured-data *@
@Kit.Page.AddJsonLd(new Dictionary<string, object> {
    { "@context", "https://schema.org"},
    { "@type", "Organization"},
    { "url", "http://www.example.com"},
    { "name", "Unlimited Ball Bearings Corp."},
    { "contactPoint", new Dictionary<string, object> {
      {"@type", "ContactPoint"},
      {"telephone", "+1-401-555-1212"},
      {"contactType", "Customer service"}
    }}
})

@* Set some OpenGraph headers *@
@Kit.Page.AddOpenGraph("title", "2sxc QuickRef Razor Typed")
@Kit.Page.AddOpenGraph("type", "website")
<p>
  This uses <code>Kit.Page.SetTitle(...)</code> and other methods to modify the HTML sent to the browser. 
  It sets various aspecs such as <code>title</code> or FavIcons.
</p>
<ol>
  <li><code>meta title</code>, <code>meta description</code>, <code>meta keywords</code> </li>
  <li>favicon</li>
  <li>some JsonLd for google</li>
  <li>OpenGraph headers for FaceBook, Twitter, etc.</li>
</ol>

Output is Invisible as it only affects the HTML Head

This sample modifies the HTML head, so it's not visible here. 

To see the effect, look at the source in the browser

  1. Set Open-Graph headers for Social Media using the IPageService

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

  2. JSON-LD Headers for SEO

    Add JSON-LD (Linked Data) headers for Google

JavaScript - Working with Razor and WebApi

A core challenge is to activate JavaScripts only when needed - and when all dependencies are loaded. This is what turnOn does. It checks if all specified JS objects exist, and then triggers the JS code.

⬇️ Result | Source ➡️

The following text will be replaced once the JS is triggered:

This example passes data to the JS, so it can be parameterized:

We can also pass in more sophisticated data:

@inherits Custom.Hybrid.RazorTyped

<p>
  The following text will be replaced once the JS is triggered: <br>
  <strong id="turnOn1-message"></strong>
</p>

@* Load the JavaScript - it will not run by itself, as the DOM might not be ready
    Note that this can be before or after the TurnOn *@
<script src="@App.Folder.Url/tutorials/js-quickref/js/turnOn1.js"></script>

@* Tell TurnOn to trigger the JS when everything is ready *@
@Kit.Page.TurnOn("window.quickReference.turnOn1Message()")

<p>
  This example passes data to the JS, so it can be parameterized:  <br>
  <strong id="turnOn2-message"></strong>
</p>

@* Tell TurnOn to trigger the JS and give it a string *@
@Kit.Page.TurnOn("window.quickReference.turnOn2Message()", data: "Hello from Razor, the page Id is" + MyPage.Id)

<p>
  We can also pass in more sophisticated data:  <br>
  <strong id="turnOn3-message"></strong>
</p>
@{
  // Create an anonymous object containing the data to send
  var turnOn3Data = new {
    domId = "turnOn3-message",
    message = "Hello from Razor...",
    pageId = MyPage.Id,
    pageUrl = MyPage.Url
  };
}
@* Tell TurnOn to trigger the JS and give it a complex object *@
@Kit.Page.TurnOn("window.quickReference.turnOn3Message()", data: turnOn3Data)

Source Code of turnOn1.js

// Make sure the object exists, which can contain various scripts for the Quick Reference
// This makes sure that if other scripts also create it, they won't interfere with each other
window.quickReference = window.quickReference || {};

window.quickReference.turnOn1Message = function () {
  // get div in html with id 'turnOn1-message' and show "Hello World!"
  const tag = document.getElementById('turnOn1-message')
  tag.innerHTML = 'Hello from turnOn1.js! This was activated using turnOn';
}

window.quickReference.turnOn2Message = function (message) {
  // get div in html with id 'turnOn1-message' and show "Hello World!"
  const tag = document.getElementById('turnOn2-message');
  tag.innerHTML = message;
}

window.quickReference.turnOn3Message = function (config) {
  // get div in html with id 'turnOn1-message' and show "Hello World!"
  const tag = document.getElementById(config.domId);
  tag.innerHTML = config.message + 
    '; PageId: ' + config.pageId + 
    "; Url: " + config.pageUrl;
}

Work with the new UniqueKey with JavaScript - new v16.04 🌟

The UniqueKey is a new feature in 2sxc 16.04 which allows you to create unique IDs for HTML elements. The value of UniqueKey is the same in all Razor and C# files for the same Content-Block.

⬇️ Result | Source ➡️

This separate Razor will create a div for the resulting message, based on the same UniqueKey which is 7ZSXd561

(script didn't run yet - this elements id is demo-uniquekey-msg-7ZSXd561)
@inherits Custom.Hybrid.RazorTyped

@{
  var buttonId = "demo-uniquekey-btn-" + UniqueKey;
  var messageId = "demo-uniquekey-msg-" + UniqueKey;
}
@* Show the button *@
<button type="button" id="@buttonId" class="btn btn-primary">
  Press to see JS find the button using UniqueKey: @buttonId
</button>

@* Create the DIV for the message - it's in another file, but shares the UniqueKey *@
@Html.Partial("./Uniquekey-Message.cshtml")

@* Trigger the script, and pass in the IDs it will need based on the UniqueKey *@
@Kit.Page.TurnOn("window.quickReference.demoUniqueQuey()", data: new { buttonId, messageId })
@* Load the script - this can be before or after the TurnOn *@
<script src="@App.Folder.Url/tutorials/js-quickref/js/unique-key.js"></script>

Source Code of Uniquekey-Message.cshtml

@inherits Custom.Hybrid.RazorTyped

<p>
  This separate Razor will create a div for the resulting message, based on the same <code>UniqueKey</code> which is <code>@UniqueKey</code>
</p>
<code id="demo-uniquekey-msg-@UniqueKey">(script didn't run yet - this elements id is <code>demo-uniquekey-msg-@UniqueKey</code>)</code>

Source Code of unique-key.js

// Make sure the object exists, which can contain various scripts for the Quick Reference
// This makes sure that if other scripts also create it, they won't interfere with each other
window.quickReference = window.quickReference || {};

// Bind a click action to the button with the unique id
window.quickReference.demoUniqueQuey = function (ids) {
  document.getElementById(ids.buttonId)
    .addEventListener("click", function () {
      const msg = 'The button was pressed. ' +
      'This was only possible thanks to the unique id using UniqueKey. ' + 
      'The ID this time was: ' + ids.buttonId + '.';

      // alert(msg);

      document.getElementById(ids.messageId).innerHTML = msg;
  });
}

Sometimes you need a UniqueKey which also depends on other objects. For example, you may need to have a UniqueKey which also uses another value - or many. This is done using @Kit.Key.UniqueKeyWith(...).

⬇️ Result | Source ➡️

  1. Unique Key with 12345: 7ZSXd561-n12345
  2. Unique Key with "hello": 7ZSXd561-s-327419862
  3. Unique Key with "bad chars in id ! % / 👍🏽": 7ZSXd561-s-1348749150
  4. Unique Key with "this is a long text and should be shortened": 7ZSXd561-s527251735
  5. Unique Key with 12345 and "hello": 7ZSXd561-n12345-s-327419862
@inherits Custom.Hybrid.RazorTyped

<ol>
  <li>
    Unique Key with <code>12345</code>:
    <code>@Kit.Key.UniqueKeyWith(12345)</code>
  </li>
  <li>
    Unique Key with <code>"hello"</code>:
    <code>@Kit.Key.UniqueKeyWith("hello")</code>
  </li>
  <li>
    Unique Key with <code>"bad chars in id ! % / 👍🏽"</code>:
    <code>@Kit.Key.UniqueKeyWith("bad chars in id ! % / 👍🏽")</code>
  </li>
  <li>
    Unique Key with <code>"this is a long text and should be shortened"</code>:
    <code>@Kit.Key.UniqueKeyWith("this is a long text and should be shortened")</code>
  </li>
  <li>
    Unique Key with <code>12345</code> and <code>"hello"</code>:
    <code>@Kit.Key.UniqueKeyWith(12345, "hello")</code>
  </li>
</ol>

If the UniqueKey is based on known object types such as Entities, this works very well. For example, you may need to loop through a list of items, and each item needs a unique key.

⬇️ Result | Source ➡️

  1. Title: Hitchhikers Guide to the Galaxy - UniqueKey: 7ZSXd561-eid7md5eRsH
  2. Title: Good Omens - UniqueKey: 7ZSXd561-eidcAcM-LSz
  3. Title: Phishing for Phools - UniqueKey: 7ZSXd561-eidlkSe34Oo
  4. Title: The Last Continent - UniqueKey: 7ZSXd561-eid_EnbtOtU
@inherits Custom.Hybrid.RazorTyped

@{
  var books = AsItems(App.Data["Books"]);
}
<ol>
  @foreach (var book in books) {
    <li>
      Title: <code>@book.Title</code> - UniqueKey: <code>@Kit.Key.UniqueKeyWith(book)</code>
    </li>
  }
</ol>

JSON

 

 

#1 Quick Reference for all APIs