笔记: ASP.NET Core视图组件

视图组件

asp.net core mvc 提供了部分视图的新替代品:视图组件。

视图组件与分布视图的主要区别在于视图组件与控制器不相关。可使用在独立于单个控制器的场景,如:菜单导航、侧边栏、分页栏等。

using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;

public class OneModelViewComponent : ViewComponent
{
    //异步方式
    public Task<IViewComponentResult> InvokeAsync(){
        return Task.FromResult<IViewComponentResult>(View(new {name="Rohmeng"}));
    }
    
    // public IViewComponentResult Invoke()
    // {
    //     ViewBag.Msg = "视图组件";
    //     return View();
    // }
}

在Shared文件夹中为视图创建Components文件夹,再创建对应组件的OneModel文件夹,把需要命名为default.cshtml的视图放入其中。

Shared --> Components --> OneModel --> default.cshtml

<h1>@Model</h1>

在其它视图中调用视图组件

@await Component.InvokeAsync("OneModel")

或者使用 Tag Helper调用视图组件,要为视图组件使用Tag Helper需要添加@addTagHelper指令和视图组件所在的程序集名称。Tag Helper通过切换到小写字母来更换名称,不使用大写字母,而是添加连字符。

@addTagHelper *, 程序集名称

<div>
    <vc:one-model />
</div>
posted @ 2019-06-27 23:33  Rohmeng  阅读(422)  评论(0编辑  收藏  举报