Razor简介
Razor引擎能够解析.cshtml文件中编写的C#脚本,APS.NET Core内置了对Razor的支持,所以使用Razor时,不需要添加任何NuGet包,只需在.cshtml文件中使用Razor时,在前面加上 @符号。例如
当前时间:@DateTime.Now
在*.cshtml文件中,也可以使用C#流程控制语句或语句块,如
- 分支类结构语句:
@if
,@switch
- 循环类结构语句:
@for
,@foreach
,@while
,do{}while()
- 语句块:
@{}
,@try
,@lock
- 其他功能语句:
@using
,@model
,@inherits
,@inject
,@functions
,@section
@for(var i=0; i<10; i++)
{
//输出10个列表项
- item-@i
-
}
常用指令说明
在MVC设计模式中,@model
指令用来定义Controller传过来的数据类型,并将其填入View的Model属性中,这样View就可获取Controller传过来的模型数据。例如:
//controller代码
public ActionResult Index(){
var user = new UserModel(){Name="张三"};
//将user模型传递给对应的View(cshtml)
return View(user);
}
//index.cshtml
//定义View中Model的类型为UserModel
@model UserModel
//这里的Model是View的内置对象,类型为UserModel,已被Controller赋值为User
名称:@Model.Name
@inject
指令用来从DI容器中获取服务
//startup.cs 注册服务
public void ConfigureServices(IServiceCollectioin services){
//注册User服务
services.AddScoped();
}
//cshtml文件从DI容器获取IUser服务
@inject IUser _IUser;
@functions
指令可以在cshtml文件中定义方法
@functions{
public T Add(T t1,T t2):where T:struct{
return t1+t2;
}
}
2+3=@Add(2,3)
View布局
View文件地址
在MVC中,Controller和View是基于约定的,Controller的Action使用View()方法返回结果页面时,约定的查找cshtml文件的顺序为:
Views/{ControllerName}/{ActionName}.cshtml
Views/Shared/{ActionName}.cshtml
比如:url地址为 http://localhost:5001/home/index 对应的Controller为HomeController,Action为Index()
public class HomeController:Controller{
public IActionResult Index(){
return View();
}
}
此时,MVC框架先去查找Views/Home/Index.cshtml 文件,如果没有,再找 Views/Shared/Index.cshtml 文件。
Layout
Razor中的Layout起到页面整体框架的作用(母版页),Layout文件放在Views/Shared/_Layout.cshtml中,要套用该Layout,需要在Razor页面中添加程序块
@ViewBag.Title
框架头
@RenderBody()
@{
Layout = "_Layout";
//ViewBag是一个Dynamic类型,在一个请求中,可以跨Controller存取数据
ViewBag.Title = "Hello World";
}
这是内容
_ViewImports.cshtml文件保存通用的@using语句
_ViewStart.cshtml文件指定Layout模板
//_ViewStart.cshtml内容
@{
//所有cshtml都套用_Layout模板
Layout = "_Layout"
}