筆記: ASP.NET Core視圖組件

視圖組件

asp.net core mvc 提供了部分視圖的新替代品:視圖組件。html

視圖組件與分佈視圖的主要區別在於視圖組件與控制器不相關。可以使用在獨立於單個控制器的場景,如:菜單導航、側邊欄、分頁欄等。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的視圖放入其中。asp.net

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

<h1>@Model</h1>

在其它視圖中調用視圖組件.net

@await Component.InvokeAsync("OneModel")

或者使用 Tag Helper調用視圖組件,要爲視圖組件使用Tag Helper須要添加@addTagHelper指令和視圖組件所在的程序集名稱。Tag Helper經過切換到小寫字母來更換名稱,不使用大寫字母,而是添加連字符。code

@addTagHelper *, 程序集名稱

<div>
    <vc:one-model />
</div>
相關文章
相關標籤/搜索