1. 什么是Razor
2. Razor C# 基本语法规则
3. 逻辑条件与循环
4. ASP.NET MVC 中 Razor 布局
razor
@
将代码块添加到页面中
You are using @Request.Broswer.Broswer!
@{ ViewBag.title = \"Home Page\"; }
@{ var myMessage = \"Hello World\"; }
@{
var name = \"Jason\";
var greeting = \"Nice to meet you, \";
var greetingMessage = greeting + name;
}
The greeting is: @greetingMessage
var
关键字,声明变量存储值
@{ var welcomeMessage = \"Welcome, new members!\"; }
@welcomeMessage
@{ var year = DateTime.Now.Year; }
@{ var myString = \"This is just an example\"; }
@{ var test = \"This is a long
string\"; } // Does not work!
@helper formatAmount(decimal amount)
{
var color = \"green\";
if (amount < 0)
{
color = \"red\";
}
@String.Format(\"{0:c}\", amount)
}
然后可以在其他地方使用helper方法,比如:
@{var amounts = new List {100, 25.50m, -40, 276.99m}
}
@foreach(decimal amount in amounts)
{
- @formatAmount(amount)
}
@{}
中的内容都会被视为C#代码如果想要添加纯文本,两种方法
@ {
//方法1
djskfadsfhadsjfk
//方法2
@: fhdshfjskhfksfs
}
输出@
符号
@ { Have a good weekend @@LA
}
//output: Have a good weekend @LA
使用@**@
@* A one-line code comment. *@
@*
This is a multiline code comment.
It can continue for any number of lines.
*@
在@{}
中使用C#的注释格式
@{
// This is a comment.
var myVar = 17;
/* This is a multi-line comment
that uses C# commenting syntax. */
}
If-else, else if 语句
@ { var price = 25; }
@if (price >= 30)
{
The price is high.
}
else if (price > 20 && price < 30)
{
The price is OK.
}
else
{
The price is low.
}
Switch 语句
@ { var day = \"Monday\"; }
@switch(day)
{
case \"Monday\":
message=\"This is the first weekday.\";
break;
case \"Thursday\":
message=\"Only one day before weekend.\";
break;
case \"Friday\":
message=\"Tomorrow is weekend!\";
break;
default:
message=\"Today is \" + day;
break;
}
For 循环
@for (int i = 0; i < 10; i++)
{
@:@i
}
@{
for (int i = 0; i < 10; i++)
{
//do something
}
}
While 循环
@{
var i = 0;
while (i < 5)
{
i += 1;
Output is: @i
}
}
Foreach 循环
//定义一个数组
@{var amounts = new List {100, 25.50m, -40, 276.99m}
}
//使用foreach遍历数组
@foreach(decimal amount in amounts)
{
- @amount
}
Views folder
@{
Layout = \"~/Views/Shared/_Layout.cshtml\";
}
@ViewBag.Title
@Styles.Render(\"~/Content/css\")
@Scripts.Render(\"~/bundles/modernizr\")
@Html.Partial(\"_header\")
@RenderBody()
@Scripts.Render(\"~/bundles/jquery\")
@RenderSection(\"scripts\", required: false)
@Html.Partial(\"_footer\")