Skip to main content
Home  › ... Razor

Razor Basics Tutorials

Tutorial HomeRazor Basics

Work with HTML Output

This uses the basic @variableName syntax. This will result in encoding html, so tags in that variable will be shown as html-source.

⬇️ Result | Source ➡️

  • this is text, it doesn't have tags
  • this string <em>has</em> html <strong>tags</strong>
@inherits Custom.Hybrid.RazorTyped

@{
  //Initial Code
  var normalText = "this is text, it doesn't have tags";
  var htmlText = "this string <em>has</em> html <strong>tags</strong>";
}

<ul>
  <li>@normalText</li>
  <li>@htmlText</li>
</ul>

⬇️ Result | Source ➡️

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

@{
  //Initial Code
  var normalText = "this is text, it doesn't have tags";
  var htmlText = "this string <em>has</em> html <strong>tags</strong>";
}

<ul>
  <li>@Html.Raw(normalText)</li>
  <li>@Html.Raw(htmlText)</li>
</ul>

Sometimes you need to conditionally add tags, in which case Razor cannot verify that open/close of tags is correct. This would normally throw an error. so you need @:.

⬇️ Result | Source ➡️

This is randomly bold or not, depending on a random event. If it's bold, you'll see a strong tag around it, otherwise not.
@inherits Custom.Hybrid.RazorTyped

@{
  //Initial Code
  var normalText = "this is text, it doesn't have tags";
  var htmlText = "this string <em>has</em> html <strong>tags</strong>";
}

<div>
  @{ var makeBold = new System.Random().NextDouble() > 0.5; }
  @if (makeBold) { 
    @:<strong> 
  }
    This is randomly bold or not, depending on a random event. If it's bold, you'll see a <code>strong</code> tag around it, otherwise not.
  @if (makeBold) { 
    @:</strong>
  }
</div>