Skip to Content
Razor Pages Syntax I
Writing C# in a Razor Page

All C# expressions are preceded with the character “@“. For example:


If your C# code needs spaces, then it must be wrapped in parentheses:

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

We can use code blocks:

@{ // C# code }

if our code exceeds one line or we want to declare variables.

@{ int num1 = 6; int num2 = 4; int result = num1 + num2; } <h3> The result of @num1 + @num2 is: @result</h3>


<h3> The result of 6 + 4 is: 10</h3>



Open a code block below @model IndexModel so that we can start writing C# code in them.


Within your code block, start by creating a string variable named firstName and assign it to your first name.


Let’s now create an int variable named age and assign it your age.


Now that we have a few assigned variables, let’s display their values on the page! Fill out our header describing your name and age.

Folder Icon

Sign up to start coding

Already have an account?