Razor简介

作者: 书上得来终觉浅 | 来源:发表于2018-10-17 17:38 被阅读26次

Razor简介

Razor引擎能够解析.cshtml文件中编写的C#脚本,APS.NET Core内置了对Razor的支持,所以使用Razor时,不需要添加任何NuGet包,只需在.cshtml文件中使用Razor时,在前面加上 @符号。例如

<p>当前时间:@DateTime.Now</p>

在*.cshtml文件中,也可以使用C#流程控制语句或语句块,如

  • 分支类结构语句:@if,@switch
  • 循环类结构语句:@for,@foreach,@while,do{}while()
  • 语句块:@{}@try,@lock
  • 其他功能语句:@using@model,@inherits,@inject,@functions,@section
<ul>
@for(var i=0; i<10; i++)
{
    //输出10个列表项
    <li>item-@i<li>
}
<ul>

常用指令说明

在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
<div>名称:@Model.Name</div>

@inject指令用来从DI容器中获取服务


//startup.cs 注册服务

public void ConfigureServices(IServiceCollectioin services){
    //注册User服务
    services.AddScoped<IUser,User>();
}

//cshtml文件从DI容器获取IUser服务
@inject IUser _IUser;

@functions指令可以在cshtml文件中定义方法

@functions{
    public T Add<T>(T t1,T t2):where T:struct{
        return t1+t2;
    }
}

<div>2+3=@Add<int>(2,3)</div>

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页面中添加程序块


<!-- _Layout模板 -->

<!DOCTYPE html>
<html>
<head>
    <title>@ViewBag.Title</title>
</head>
<body>
    <header>
        框架头
    </header>
    <div>
        @RenderBody()
    </div>
    <footer>
        框架尾
    </footer>
</body>
</html>

@{
    Layout = "_Layout";
    //ViewBag是一个Dynamic类型,在一个请求中,可以跨Controller存取数据
    ViewBag.Title = "Hello World";
}

<div>这是内容</div>

_ViewImports.cshtml文件保存通用的@using语句

_ViewStart.cshtml文件指定Layout模板

//_ViewStart.cshtml内容
@{
    //所有cshtml都套用_Layout模板
    Layout = "_Layout"
}

相关文章

网友评论

    本文标题:Razor简介

    本文链接:https://www.haomeiwen.com/subject/ilbrzftx.html