ASP.NET Core 5.0 MVC Razor Syntax Edit

Murugan Andezuthu Dharmaratnam | 18 January 2021 | 170

Introduction

Razor is one of the view engines supported in ASP.NET MVC. Razor allows you to write a mix of HTML and server-side code. .cshtml is the file extension.

Inline expression

Start with @ symbol to write server-side C#.

Razor syntax

@DateTime.Now.ToShortDateString()

Output

Razor syntax
08-02-2021

Multiline expression

@{
    var date = DateTime.Now.ToShortDateString();
    var message = "Hello World";
}

Today's date is: @date

@message

Output

Today's date is: 08-02-2021
Hello World!

Display Text from Variable

@{
    var date = DateTime.Now.ToShortDateString();
    string message = "Hello World!";
    @:Today's date is: @date 
@message }

output

Today's date is: 08-02-2021
Hello World!

if-else condition

@if(DateTime.IsLeapYear(DateTime.Now.Year) )
{
    @DateTime.Now.Year @:is a leap year.
}
else { 
    @DateTime.Now.Year @:is not a leap year.
}

Output

2021 is not a leap year.