Razor Syntax

On my first Razor project, I made the mistake of treating Razor pages as static HTML pages, rather than taking advantage of all cool features of embedding server code directly into webpages. In doing this, I used C# plenty, but I did it in the old-fashion was of keeping it in the cshtml.cs code-behind file. I used these code-behind files to handle events, but not much more.

This post shows different ways that you can embed C# directly into your Razor web pages.

First, we need a way to indicate a transition from HTML to C#. It is similar to how we tell the browser that we are going to add JavaScript directly on an HTML page by adding a the <script> tag. However, it is different in an important way. The C# code in your implicit expressions, explicit expressions, and code blocks is executed on the server instead of the browser.

If you want to write C# that executes in the browser, then you should check out Blazor. It runs C# directly in the browser using WebAssembly. What??? That seems like black magic. The only code that should ever run in the browser is JavaScript, or so we have been told in the past. Even TypeScript is transpiled into JavaScript by the compiler before being sent to the browser for execution. There are no plug-ins required. I will cover Blazor in a future post. Maybe it is going to be the next big thing, but I digress.

Back to Razor. The way we denote a transition to C# is with the @ symbol.

Implicit Expressions

We can add implicit Razor expressions that start with @ and are followed by C# code. This example shows how to run C# that returns the value of a variable that is defined in the code-behind file.

Here is the embed code in the cshtml file:

<div>@Model.RequestId</div>

And here is the code-behind file that defines and sets the variable “RequestID”:

public string RequestId { get; set; }
public void OnGet()
        {
            RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
        }

You can also embed the results of methods in your code. In the following example, we call the “IsLeapYear()” method of the DateTime type. We pass in the parameter ‘2016’ to the method IsLeapYear(2016)

<p>Is 2016 a leap year? @DateTime.IsLeapYear(2016)</p>

This will render in your browser as:

Explicit Expressions

You can add explicit Razor expressions. With explicit expressions, we still use the @ symbol, but we also include parentheses around the expression.

<p>Last week this time: @(DateTime.Now - TimeSpan.FromDays(7))</p>

Content within the @() block is evaluated on the server and sent back to the browser to render. Using explicit expressions, we can use spaces. Notice that the block above contains spaces. Whereas you cannot use spaces in implicit expressions. The above code looks like this in the browser:

If we inspect the code, we see plain HMTL.

<p>Last week this time: 10/19/2019 9:20:30 AM</p>

Notice the absence of C#. Again, this is because the execution of this code happens on the server. It returns pure HTML to the browser for rendering. Sorry to keep repeating this, but it is crucial to understand.

Razor Code Blocks

Razor code blocks look similar to explicit expressions. At first glance, it appears the only difference is the use of braces{} instead of parentheses() for setting bounds to the code. However, explicit expressions and code blocks behave differently. Unlike expressions, the C# code inside the code block does not directly change the content of the web page. It only executes the code. However, we can use code blocks to set variables that then indirectly update the content sent to the browser. It is a subtle but essential distinction.

In the example below, the code is executed, and the variable ‘quote’ is defined. It is then rendered using <p>@quote</p>

@{
    var quote = "It's a dangerous business, Frodo, going out your door. - Bilbo Baggins";
}

<p>@quote</p>

@{
    quote = "“It's the job that's never started as takes longest to finish. - Sam Gamgee";
}

<p>@quote</p>

The code returns the following HTML to the browser:

<p>It's a dangerous business, Frodo, going out your door. - Bilbo Baggins</p>
<p>It's the job that's never started as takes longest to finish. - Sam Gamgee</p>

Here is another example of embedding code in the markup file, this time utilizing a complex object. We create a new C# object of type person and assign it a name and age value. In the C# constructor for this object (in the code-behind), we have defined a way to instantiate with name and age parameters:

@{
    var john = new Person("John", 33);
}

<p>Age: @(john.Age)</p>

If you weren’t using an explicit expression, the browser would treat Age@john.Age as an email address! Instead, the following is provided to the browser to render:

 <p>Age: 33</p>

The following code sample demonstrates how we use semicolons to end each line of C# code. However, semicolons are not needed for inline expressions:

<!-- Single-statement block -->
@{ var theMonth = DateTime.Now.Month; }

<!-- Multi-statement block -->
@{
    var temperature = 70;
    var weatherMessage = "Hello, it is a beautiful " + temperature + " degrees outside.";
}

<!-- Inline expression, so no semicolon -->
<p>Today's weather: @weatherMessage</p>

Code that Uses Conditional Logic

Finally, you can also add logic gates in your code blocks. For example, you can decide what to show on your page based on conditions.

@{
   string result = ""; 
   if(IsUserAuthenticated)  
   {
      result = "Hello, " + userName +"! Please click below to view your most recent reports.";
   }
   else
   {
      result = "Welcome to our site.  Please login to see your reports.";
   }
}

<div>@result</div>

Notice on line 2 above that we are using strong typing (string) to define the result variable. This is not possible in JavaScript (which is dynamically typed), but it is possible in C#.

Notice on line 3 above that we are referencing ‘IsUserAuthenticated’. I have not defined IsUserAuthenticated as a C# variable on this page, so it must be referencing something else. What, then, is being referenced? It turns out that IsUserAuthenticated is a global JavaScript variable. In other words, your C# can access JavaScript variables! This can be very useful.

The following shows how I set IsUserAuthenticated (a JavaScript variable) using a C# code block in the .cshtml file:

@if(User.Identity.IsAuthenticated)
{
 <script>
  var userAuthorized = true;
 </script> 
}
else
{
 <script>
  var userAuthorized = false;
 </script> 
}

How Can We Help? Find out how Lone Peak Software can help with Office 365, SharePoint and Azure.

%d bloggers like this:
search previous next tag category expand menu location phone mail time cart zoom edit close