视图组件
就是分部视图里加上相应的代码逻辑,如从数据库中取出数据后for显示出来,如果是用一般的分部视图的话得在每个控制器里都取数据的,这时可以用视图组件把代码取数据抽出来,步骤如下:
建立ViewComponents目录
在里面建立类AllAcc
using System;
using Microsoft.AspNetCore.Mvc;
namespace Niunan.Net7.Charge.Web.ViewComponents
{
public class AllAcc : ViewComponent
{
DAL.Interface.IAccount dal;
public AllAcc(DAL.Interface.IAccount dal)
{
this.dal = dal;
}
public async Task<IViewComponentResult> InvokeAsync()
{
var items = dal.GetListArray("isuse=1 order by id asc");
return View(items);
}
}
}
视图文件夹里的Shared里建立 Components 目录,在里面再建立 AllAcc 目录,里面建立 Default.cshtml 文件
@model IEnumerable<Niunan.Net7.Charge.Model.Account>
@foreach (Niunan.Net7.Charge.Model.Account item in Model)
{
<div class="layui-btn layui-btn-primary">@item.accname
@if (item.balance < 0)
{
<span class="zhichu-color">¥@item.balance.ToString("f2")</span>
}
else
{
<span>¥@item.balance.ToString("f2")</span>
}
</div>
}
<div class="layui-btn layui-btn-warm">总额 ¥@Model.Sum(a=>a.balance).ToString("f2")</div>
在cshtml中使用:
@await Component.InvokeAsync("AllAcc")