Blazor_WASM Part 2: Razor Syntax
Razor is a markup syntax for embedding .NET-based code into web pages. Razor syntax consists of Razor markup, C#, and HTML. Razor can be found in the Razor Components file ( .razor
). Razor syntax is similar to the templating engines of various JavaScript single-page application (SPA) frameworks (such as Angular, React, VueJs, and Svelte). This article introduces Razor common syntax for Razor files.
Razor syntax
@*直接输出变量*@
<p> @Name</p>
@*如果就像输出@,则使用另个@*@
<p> @@Name</p>
@*如果是明显的邮箱格式则按邮箱格式输出*@
<p>[email protected]</p>
@*虽然是邮箱格式,但是两个@会重新将Name作为属性*@
<p>123@@Name.com</p>
@*如果是邮箱格式,但是想输出Name属性可以用括号*@
<p>123@(Name).com</p>
@*razor代码块*@
@*代码块内的 C# 代码不会呈现*@
@code {
public string Name { set; get; } = "Test";
public class Student
{
public string Name { set; get; }
public string School{ set; get; }
}
string GenericMethod<T>()
{
return typeof(T).Name;
}
public Student stu = new Student() { Name = "Jerry" ,School = "yucai"};
public int value { set; get; } = 3903;
}
Razor Implicit Expressions
@*隐式 Razor 表达式,可以直接使用.*@
@*但是隐式表达式不能使用泛型*@
<p>@stu.Name</p>
Razor display expressions
@*显式表达式*@
<p>@(stu.Name)显式</p>
<p>@(stu.Name + stu.School)显式</p>
@*可以调用私有方法*@
<p>@(GenericMethod<int>())泛型</p>
cycle
@*for循环*@
@for (int i = 0; i < 3; i++)
{
<p>第@(i)个</p>
<p>@Name</p>
}
control structure
@if (value % 2 == 0)
{
<p>The value was even.</p>
}
@*else 和 else if 不需要 @ 符号:*@
@if (value % 2 == 0)
{
<p>The value was even.</p>
}
else if (value >= 1337)
{
<p>The value is large.</p>
}
else
{
<p>The value is odd and small.</p>
}
@switch (value)
{
case 1:
<p>The value is 1!</p>
break;
case 1337:
<p>Your number is 1337!</p>
break;
default:
<p>Your number wasn't 1 or 1337.</p>
break;
}
using block
@*自动释放变量*@
@*@using (FileStream fs = new FileStream(".",FileMode.OpenOrCreate))
{
}
exception catch block
@try
{
throw new InvalidOperationException("You did something invalid.");
}
catch (Exception ex)
{
<p>The exception message: @ex.Message</p>
}
finally
{
}
characteristic
Each Razor will be compiled into a class, and a feature can be added to the class
@attribute [Authorize]
implement the interface
@implements IDisposable
inheritance class
@inherits CustomRazorPage<TModel>
defined as generic
@typeparam TEntity where TEntity : class
routing
Specifies that the Razor component should handle the request directly
@page "/test"
reference namespace
@using Microsoft.AspNetCore.Authorization
define namespace
The first letter of the namespace must be capitalized
@namespace Mynamespace
dependency injection
@inject Logger<Test> logger
等价于 private readonly Logger<Test> logger;
public Test(Logger<Test> log)
{
logger = log
}