Razor and razor
Preface:
The core of the Razor engine is to identify the @ symbol and angle brackets:
1. <...> </...>
2. <.../>
[For more information, see the example below.]
@for (int i = 0; i < 5; i++)
{
<test>i</test>
}
Basic Syntax: Syntax 1 ,@()
Expression
@ (1 = 0? "1 equals 0": "1 not equal to 0 ")
Syntax 2 ,@{}
Statement Block
@{
var now = DateTime.Now;
if (now.Hour.CompareTo(12) < 0)
{
<Span> morning </span>
}
else
{
<Span> afternoon </span>
}
}
Syntax 3 ,@
1. @ directly follows the variable output content
2. @ directly follow the return value of the method output method with returned values
3. if-else, switch, for, foreach, while, do-while and other flow control statements
@now.Hour<br />
@now.ToShortDateString()<br />
@if (now.Hour.CompareTo(12) < 0)
{
<Span> morning </span>
}
else
{
<Span> afternoon </span>
}
<br />
@for (int i = 0; i < 5; i++)
{
<span>@i</span>
}
Special scenarios: @ note 1. The programming language must be isolated from the output string. 2. You cannot call a method without a return value. The solution is to use the statement block @{}.
<Span> cannot switch to the @ now. Programming Language </span> <br/> <Span> cannot switch to the @ now. Programming Language </span> <br/> @{ RazorTestClass.SayHello(); } public class RazorTestClass { public static void SayHello() { return; } public static string SayHello<T>(T t) { return t.ToString(); } } |
Syntax 4: @ helper
Declaration Method
@helper paging(uint itemCount,uint pageSize,uint pageIndex)
{
uint totalPagesCount = itemCount%pageSize == 0 ? itemCount/pageSize : itemCount/pageSize + 1;
if (0 ==
totalPagesCount
)
{
totalPagesCount = 1;
}
for (
uint i = 1; i <= totalPagesCount; i++)
{
if (
i == pageIndex)
{
<a class="pagination current" href="#?pageIndex=@i">@i</a>
}
else
{
<a class="pagination" href="#?pageIndex=@i">@i</a>
}
}
}
@paging(51, 10, 3)
Syntax 5 ,@**@
Note
@*
This is a comment
*@
Syntax 6. Razor built-in labels <text> </text>
Used to directly output content
@for (int i = 0; i < 5; i++)
{
<text>@i</text>
}
Syntax 7. escape characters
Example:
@@
@ Class
@{
@: Escape Character @@
}
Supplement:
The output HTML of the Razor engine will be escaped by default. It is most convenient to use the html. Raw () method without escaping the output.
@{
Var str = "<div style = 'color: red'> will I be escaped? </Div> ";
}
@str
@Html.Raw(str)