C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
ASP.NET Razor Code BlocksCode block is used to enclose C# code statements. It starts with @ (at) character and is enclosed by {} (curly braces). Unlike expressions, C# code inside code blocks is not rendered. The default language in a code block is C#, but we can transit back to HTML. HTML within a code block will be rendered as HTML. Example// Index.cshtml @{ Layout = null; var name = "John"; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> <h2>My name is: @name </h2> </body> </html> It produces the following output. Implicit transitionsC# is default language in Razor code block. HTML written within code block is rendered as HTML, this is called implicit transition. Razor code blocks implicit transitions HTML code and render to the view page. In the following code, HTML is written and it executes without error. // Index.cshtml @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> @{ var name = "JavaTpoint"; <h4>Welcome to the @name </h4> } </body> </html> It produces the following output. Explicit delimited transitionSometimes, when we define a sub-section of a code block that should render HTML, surround the characters to be rendered with the Razor <text> tag. It is mandate to use <text> tag. Otherwise, it throws a compile time error. See the following code. // Index.cshtml @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Index</title> </head> <body> @for (var i = 0; i < 5; i++) { <text>i= @i </text> <br/> } </body> </html> It produces the following output.
Next TopicASP.Net Razor Control Structures
|