C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ASP.NET Razor Code ExpressionsRazor 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 @{ Layout = null; var coursename = "Java Collection"; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <h2>I want to learn @coursename </h2> </body> </html> Produce the following output. Output: Implicit Razor ExpressionsImplicit Razor expression starts with @ (at) character followed by C# code. The following example demonstrates about implicit expressions. // Index.cshtml @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <p>Current Time is: @DateTime.Now.ToString("T")</p> </body> </html> It produces the following output. Output: Explicit Razor ExpressionsExplicit 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 @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <p>2 + 5 = @(2+5)</p> </body> </html> It produces the following output. Output: Razor Expression EncodingRazor 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 @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> Html.Raw("<script>alert('System Failure!')</script>") </body> </html> It produces the following output. Output: In the following example, we are encoding JavaScript script. // Index.cshtml @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> @("<script>alert('this is alert box')</script>") </body> </html> Now, it produces the following output. Output: This time razor engine encodes the script and return as a simple HTML string.
Next TopicASP.Net Razor Code Blocks
|