美文网首页
ViewComponent的简单使用

ViewComponent的简单使用

作者: 天马行空_9f6e | 来源:发表于2020-04-26 10:59 被阅读0次

    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

    相关文章

      网友评论

          本文标题:ViewComponent的简单使用

          本文链接:https://www.haomeiwen.com/subject/gzhdwhtx.html