View Component的主要作用的视图与业务逻辑的复用
View Component与Partial View的功能类似,但是Partial View只是视图的复用,业务逻辑还是在控制器的Action实现
View Component可以说包含View和Controller,可以写视图和业务逻辑
首先,在项目新建ViewComponents文件夹
新建UserInfoViewComponent类继承自ViewComponent
public class UserInfoViewComponent : ViewComponent
{
public UserInfoViewComponent(IUserInfoService userInfoService)
{
UserInfoService = userInfoService;
}
public IUserInfoService UserInfoService { get; }
public async Task<IViewComponentResult> InvokeAsync(string arg)
{
ViewBag.Arg = arg;
var userInfo = await UserInfoService.GetAll();
return View(userInfo);
}
}
其中InvokeAsync方法是实现方法,有无参数都可
在Views/Shared/Components/UserInfo下新建Default.cshtml文件
@model IQueryable<UserInfo>
<h3>@ViewBag.Arg</h3>
@foreach (var item in Model)
{
<tr>
<td>@item.Id</td>
<td>@item.Name</td>
<td>@item.Age</td>
</tr>
}
在UserInfo的Index视图使用
@{
ViewData["Title"] = "Index";
}
<h1>Index</h1>
<table class="table">
<tr>
<th>ID</th>
<th>姓名</th>
<th>年龄</th>
</tr>
@await Component.InvokeAsync("UserInfo",new { arg = "用户信息" })
</table>
如果想用Tag Helper,需要在_ViewImports.cshtml文件添加本项目程序集
@addTagHelper *, DotNetCoreTest
然后就可以这样使用了
<vc:user-info arg="用户信息"></vc:user-info>
微软官方文档
https://docs.microsoft.com/zh-cn/aspnet/core/mvc/views/view-components