# 23.3、Razor 视图引擎

## 视图引擎

自.NET Framework开始，在ASP.NET MVC框架中就引入了 `RazorEngine` ，也就是视图引擎，通常我们的视图是采用 `.cshtml` 文件进行编写。

由于我们是前后端分离的 `WebAP`I 项目，所以并没有引入完整的 `asp.net core mvc` 框架，所以，今天在 `Hoa` 框架中集成 `RazorEngine` 功能

## 简单入门

### **非强类型**

```csharp
var templateText = @"Hello @Model.Name.";
var result = RazorEngineHelper.RunCompile(templateText, new { Name = "Hoa" }); // => Hello Hoa.
```

**由于编辑模板需要付出昂贵的性能代价，所以 `Hoa` 框架只在首次编译模板后就将模板缓存起来并生成 `.dll`文件。这样就无需担心后续性能问题了。**

### **强类型模型**

```csharp
var templateText = @"Hello @Model.Name.";
var result = RazorEngineHelper.RunCompile<Model>(templateText, new Model{ Name = "Hoa" }); // => Hello Hoa.
```

### **加载`.cshtml`文件**

```csharp
// 非强类型
var cshtmlPath = "你的.cshtml完整路径";
var result = RazorEngineHelper.RunCompileViewPath(cshtmlPath, new { Name = "Hoa" }); // => Hello Hoa.

// 强类型
var result = RazorEngineHelper.RunCompileViewPath<Model>(cshtmlPath, new Model{ Name = "Hoa" }); // => Hello Hoa.
```

## 高级入门

Hoa 内置的 `Razor 视图引擎` 支持完整的 ASP.NET Core 3.x 语法，比如

### **自定义方法**

```markup
<area>
    @{ RecursionTest(3); }
</area>

@{
  void RecursionTest(int level)
  {
    if (level <= 0)
    {
        return;
    }

    <div>LEVEL: @level</div>
    @{ RecursionTest(level - 1); }
  }
}
```

### **强类型方法调用**

#### 模板定义

```markup
Hello @A, @B, @Decorator(123)
```

#### 强类型模型

```markup
public class CustomModel
{
    public int A { get; set; }
    public string B { get; set; }

    public string Decorator(object value)
    {
        return "-=" + value + "=-";
    }
}
```

#### 编译模板

```csharp
var result = RazorEngineHelper.RunCompile<CustomModel>(templateText, u => {
    u.A = 10,
    u.B = "Hoa"
});
```

### **引入程序集**

#### 模板定义

```markup
@using System.IO

<div>@Model.Name</div>
<div>@Path.GetFullPath("~/Views/Home.cshtml")</div>
```

### 编译模板

```csharp
var result = RazorEngineHelper.RunCompile(templateText
                            , new { Name = "Hoa" }
                            ,typeof(System.IO.Path));
```

更多关于RazorEngineCore [可查看官方文档](https://github.com/adoconnection/RazorEngineCore)。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://monksoul.gitbook.io/hoa/qitagongneng/razorshituyingqing.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
