Javatpoint Logo
Javatpoint Logo

ASP.NET Razor Code Expressions

Razor syntax is widely used with C# programming language. To write C# code into a view use @ (at) sign to start Razor syntax. We can use it to write single line expression or multiline code block. Let's see how we can use C# code in the view page.

The following example demonstrate code expression.

// Index.cshtml

Produce the following output.

Output:

ASP Razor code expression 1

Implicit Razor Expressions

Implicit Razor expression starts with @ (at) character followed by C# code. The following example demonstrates about implicit expressions.

// Index.cshtml

It produces the following output.

Output:

ASP Razor code expression 2

Explicit Razor Expressions

Explicit Razor expression consists of @ (at) character with balanced parenthesis. In the following example, expression is enclosed with parenthesis to execute safely. It will throw an error if it is not enclosed with parenthesis.

We can use explicit expression to concatenate text with an expression.

// Index.cshtml

It produces the following output.

Output:

ASP Razor code expression 3

Razor Expression Encoding

Razor provides expression encoding to avoid malicious code and security risks. In case, if user enters a malicious script as input, razor engine encode the script and render as HTML output.

Here, we are not using razor syntax in view page.

// Index.cshtml

It produces the following output.

Output:

ASP Razor code expression 4

In the following example, we are encoding JavaScript script.

// Index.cshtml

Now, it produces the following output.

Output:

ASP Razor code expression 5

This time razor engine encodes the script and return as a simple HTML string.







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA