Razor

一个 cshtml文件,就是一个RazorPage对象

Microsoft.AspNetCore.Mvc.Razor : https://docs.microsoft.com/zh-cn/dotnet/api/microsoft.aspnetcore.mvc.razor.razorpage?view=aspnetcore-3.1 

IRazorPage-RazorPageBase-RazorPage

 

生成razor页面

razor页面包含view+controll,比mvc更轻量级,每个 Razor 页面都是一对文件

  • 一个 .cshtml 文件,其中包含使用 Razor 语法的 C# 代码的 HTML 标记。
  • 一个 .cshtml.cs 文件,其中包含处理页面事件的 C# 代码

头部必须以@page开始。@page使文件转换为一个 MVC 操作 ,这意味着它将直接处理请求,而无需通过控制器处理。 @page 必须是页面上的第一个 Razor 指令

 只生成一个 Test.cshtml

生成一个Test.cshtml和Test.cshtml.cs

 

路由功能

/Pages/Index.cshtml / 或 /Index
/Pages/Contact.cshtml /Contact
/Pages/Store/Contact.cshtml /Store/Contact
/Pages/Store/Index.cshtml /Store 或 /Store/Index

 

通用模板页

如果页面没有指明

@{
    Layout = null;
}

则默认使用Shared/_Layout.cshtml 下的模板

 

 

代码块

@{
    var greeting = "Welcome to our site!";
    var weekDay = DateTime.Now.DayOfWeek;
    var greetingMessage = greeting + " Today is: " + weekDay;
}

<p>The greeting is: @greetingMessage</p>

 

循环控制

判断

if

@{var price=25;}
<html>
<body>
@if (price>=30)
  {
  <p>The price is high.</p>
  }
else if (price>20 && price<30) 
  {
  <p>The price is OK.</p>
  }
else
  {
  <p>The price is low.</p>
  }    
</body>
</html>

switch

@{
var weekday=DateTime.Now.DayOfWeek;
var day=weekday.ToString();
var message="";
}
<html>
<body>
@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;
}
<p>@message</p>
</body>
</html>

循环

for

<html>
<body>
@for(var i = 10; i < 21; i++)
    {<p>Line @i</p>}
</body>
</html>

foreach

<html>
<body>
<ul>
@foreach (var x in Request.ServerVariables)
    {<li>@x</li>}
</ul>
</body>
</html>

While

<html>
<body>
@{
var i = 0;
while (i < 5)
    {
    i += 1;
    <p>Line #@i</p>
    }
}
</body>
</html>

 

posted @ 2018-08-17 23:07  富坚老贼  阅读(345)  评论(0编辑  收藏  举报