前言
之前写过一篇 ASP.NET Core – View Component 里面有提到, View Component 是 Partial View 的加强版.
多了一个 .cs 可以写逻辑. 那如果我们不需要那么复杂就可以使用简化版的 Partial View 了.
重点
1. 一个 View .cshtml, 一个 View Model .cs
2. 用 Tag Helper 或者 IHtmlHelper 调用
3. view name 查找 view file 路径
Create View (.cshtml) and ViewModel (.cs)
files
微软的命名规范开始会有下划线, 但我没有 follow
内容
.cshtml 里面不可以用 @page 哦.
调用
Index.cshtml
@page @model IndexModel @{ ViewData["Title"] = "Home page"; var viewModel = new HelloWorldPartialViewModel { Value = "Value" }; } <partial name="HelloWorldPartial" model="@viewModel" /> <partial name="/Pages/HelloWorldPartial.cshtml" model="@viewModel" /> @await Html.PartialAsync("HelloWorldPartial", viewModel) @await Html.PartialAsync("/Pages/HelloWorldPartial.cshtml", viewModel)
1. Tag Helper <partial> 调用, 使用 View Name
2. Tag Helper <partial> 调用, 使用 View Path
3. IHtmlHelper PartialAsync 调用, 使用 View Name
4. IHtmlHelper PartialAsync 调用, 使用 View Path
我推荐使用第 2 个方式.
View Name 查找 View File
上面 5 个是查找路线.
1. same folder
2. ancestor's folders (祖先 folder 都可以)
3. root /Shared 里面
4. root /Pages/Shared 里面
5. root Views/Shared 里面
我一向不鼓励依赖 ASP.NET Core 的这种潜规则查找的. 通常不符合正常的开发 folder structure.
以 View Component 的比较
我个人倾向于统一使用 View Component 就够了. 不要用 Partial View.
View Component 在调用上比 Partial View 直观, 可以通过 atrribute 拆分 parameters
Partial View 只能传一个 View Model 对象. 写起来很丑.
View Component 唯一的缺点就是一定要有一个 .cs 而且需要把 parameters mapping to View Model (很繁琐的代码), 这个扣分.
但我觉得无伤大雅, 毕竟是封装起来的. 重点是对消费者友好才加多分.