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:
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:
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:
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:
In the following example, we are encoding JavaScript script.
// Index.cshtml
Now, it produces the following output.
Output:
This time razor engine encodes the script and return as a simple HTML string.