ViewComponent的简单使用

2020-04-26  本文已影响0人  天马行空_9f6e

1、新建一个类,并且继承ViewComponent类,定义一个名为InvokeAsync方法在该方法中写逻辑,类似Controller的写法

public class CinemaCountViewComponent : ViewComponent

    {

        private readonly ICinemaService cinemaService;

        public CinemaCountViewComponent(ICinemaService cinemaService)

        {

            this.cinemaService = cinemaService;

        }

        public async Task<IViewComponentResult> InvokeAsync()

        {

            var cinemas = await cinemaService.GetAllAsync();

            return View(cinemas.Count());

        }

    }

2、在Views\Shared文件夹下建立Components文件夹,并且在Components文件夹下再以刚定义的组件类的名字CinemaCountViewComponent的前缀CinemaCount建立文件夹,再在CinemaCount文件夹下建立Default.cshtml文件

3、Default.cshtml页面内容

4、在其他页面引用组件,用下图第一种方式没问题,如果要用第二种方式,需要在_ViewImports.cshtml文件中,添加TagHelper

上一篇下一篇

猜你喜欢

热点阅读