s

ASP.NET Core 5.0 MVC Razor Syntax edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 18 January 2021 | 2864

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.