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