what
试图组件是ASP.NET Core MVC中的新特性,类似于部分视图,但是它更加强大。驶入组件不使用模型绑定,并且仅依赖于调用它时所提供的数据。
how
创建视图组件类
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Web.ViewComponents
{
[ViewComponent(Name = "TopicRankList")]
public class TopicRankList : ViewComponent
{
public IViewComponentResult Invoke()
{
return View();
}
}
}
视图搜索路径
视图组件的默认视图名称是Default,这意味着你的视图文件通常名为Default.cshtml,可以在创建视图组件结果或调用View方法时指定其他视图名称。
视图组件运行时会在以下路径中搜索视图:
Views//Components//
Views/Shared/Components//
所以根据创建的类,我们需要在Views/Shared/Components/TopicRankList文件夹中创建Default.cshtml文件。
@{
ViewData["Title"] = "Default";
}
<h1>Default</h1>
调用视图
@await Component.InvokeAsync("TopicRankList")
看看
谢谢亲